Cast generic type parameter to a specific type in C#

后端 未结 7 1036
终归单人心
终归单人心 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:14

    You can use Convert.ChangeType

    SomeClass obj2 = (SomeClass)Convert.ChangeType(t, typeof(SomeClass));
    

    Although, keep in mind that this will throw an exception if a cast is invalid.

提交回复
热议问题