Cast generic type parameter to a specific type in C#

后端 未结 7 1035
终归单人心
终归单人心 2021-01-01 17:42

If you need to cast a generic type parameter to a specific type we can cast it to a object and do the casting like below,

void SomeMethod(T t)
{
    SomeClas         


        
7条回答
  •  星月不相逢
    2021-01-01 18:03

    Using as:

    SomeClass obj2 = t as SomeClass;
    

    This would not throw an exception and t would be null if the cast fails.

    I don't really know what you're trying to do, but I hope that you're not missing the point of Generics here.

    If your intention is to restrict the method to type SomeClass and descendants:

    void SomeMethod(T t)  where T : SomeClass
    

提交回复
热议问题