泛型方法在C#检查类型参数 [英] Checking type parameter of a generic method in C#

查看:245
本文介绍了泛型方法在C#检查类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能做这样的事情在C#中:

 公共无效DoSomething的< T>(T T)
{
    如果(T是MyClass的)
    {
        MyClass的MC =(MyClass的)笔
        ...
    }
    否则,如果(T是列表与LT; MyClass的>)
    {
        清单< MyClass的> LMC =(列表< MyClass的>)笔
        ...
    }
}


解决方案

是:

 如果(typeof运算(T)== typeof运算(MyClass的))
{
    MyClass的MC =(MyClass的)(对象)吨;
}
否则,如果(typeof运算(T)== typeof运算(列表< MyClass的>))
{
    清单< MyClass的> LMC =(列表< MyClass的>)(对象)吨;
}

这是有点奇怪,你需要通过投反对去,但是这只是泛型的工作方式 - 有没有那么多的转换,从你可能期望一个泛型类型

当然另一个替代方法是使用正常执行时检查:

  MyClass的MC = T作为MyClass的;
如果(MC!= NULL)
{
    // ...
}
其他
{
    清单< MyClass的> LMC = T作为列表< MyClass的取代;
    如果(LMC!= NULL)
    {
        // ...
    }
}

这将表现不同的第一code座,如果 T 是空的,当然。

我的尝试的避免这种code哪里可能的,但是 - 可能有必要的时候,但是泛型方法的想法是能写的通用的code这对于任何类型的工作方式相同。

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

public void DoSomething<T>(T t)  
{
    if (T is MyClass)
    {
        MyClass mc = (MyClass)t 
        ...
    }
    else if (T is List<MyClass>)
    {
        List<MyClass> lmc = (List<MyClass>)t
        ...
    }
}

解决方案

Yes:

if (typeof(T) == typeof(MyClass))
{
    MyClass mc = (MyClass)(object) t;
}
else if (typeof(T) == typeof(List<MyClass>))
{
    List<MyClass> lmc = (List<MyClass>)(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<MyClass> lmc = t as List<MyClass>;
    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.

这篇关于泛型方法在C#检查类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆