开发者

C# Generics - Accepting different types

I am trying to write a generic method so I can avoid code duplicati开发者_StackOverflow中文版on. The generic method has to be able to accept one of three different grid view types however I cannot get the following cast to work at the start of the generic method;

var grid;

            if (typeof(T) == typeof(GridView))
            {
                grid = (GridView)gridView;
            }
            else if (typeof(T) != typeof(BandedGridView))
            {
                grid = (BandedGridView)gridView;
            }
            else if (typeof(T) != typeof(AdvBandedGridView))
            {
                grid = (AdvBandedGridView)gridView;
            }
            else return;

How can I cast "grid" to either of the three types so I can then do something with them. I am still trying to grasp the idea and concept behind Generics.


If BrandedGridView and AdvBrandedGridView both inherit from GridView you can add a constraint to your generic

...<T> where T : GridView

If not you can use Convert.ChangeType:

Try Convert.ChangeType:

if (typeof(T) == typeof(GridView))
{
    var grid = (GridView)Convert.ChangeType(gridView, typeof(GridView));
}
elseif (typeof(T) == typeof(BrandedGridView))
{
    var grid = (BrandedGridView)Convert.ChangeType(gridView, typeof(BrandedGridView));
}


You want to constrain type T to something (likely GridView as 2 other types are likely derive from it) so C# knows what method the T has, otherwise it is just of type Object.

public class MyClass<T> where T : GridView

Please read article about generic on MSDN to get more details - http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx#csharp_generics_topic4

Note: As mentioned above C# is not JavaScript and "var" does not mean "a type" it is just shorter way to declare object of type of the right side. I.e. in var my = new List() var is synonim for List.


"methods are identical except for the parameter type"

I think you should just make a new method that has the different parameter type of the view as the actual parameters. They're the ones that are different after all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜