Checking type parameter of a generic method in C#

前端 未结 4 1103
再見小時候
再見小時候 2020-12-02 19:56

Is it possible to do something like this in C#:

public void DoSomething(T t)  
{
    if (T is MyClass)
    {
        MyClass mc = (MyClass)t 
               


        
4条回答
  •  遥遥无期
    2020-12-02 20:09

    Yes:

    if (typeof(T) == typeof(MyClass))
    {
        MyClass mc = (MyClass)(object) t;
    }
    else if (typeof(T) == typeof(List))
    {
        List lmc = (List)(object) t;
    }
    

    It's slightly odd that you need to go via a cast to object, but that's just the way that generics work - there aren't as many conversions from a generic type as you might expect.

    Of course another alternative is to use the normal execution time check:

    MyClass mc = t as MyClass;
    if (mc != null)
    {
        // ...
    }
    else
    {
        List lmc = t as List;
        if (lmc != null)
        {
            // ...
        }
    }
    

    That will behave differently to the first code block if t is null, of course.

    I would try to avoid this kind of code where possible, however - it can be necessary sometimes, but the idea of generic methods is to be able to write generic code which works the same way for any type.

提交回复
热议问题