Cast generic type parameter to a specific type in C#

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

    If there is no relation between the input type T and the target types TypeA or TypeB (using parameter contraints), and we are looking purely at the casting-problem, the answer is simple:

    No, there is no better way than the method you are using!!!

    I do agree with some other people, if you are doing more operations on that object, you might wanna choose a different design.

提交回复
热议问题