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)
{
SomeClass obj2 = (SomeClass)(object)t;
}
Is there a better way to achieve this, rather than casting it to an object and then to a specific type?
Problem:
I have a generic function which accepts a generic type parameter, inside the function based on a type checking I do some operations like below:
void SomeMethod(T t)
{
if (typeof(T).Equals(typeof(TypeA)))
{
TypeA = (TypeA)(object)t;
//Do some operation
}
else if (typeof(T).Equals(typeof(TypeB)))
{
TypeB = (TypeB)(object)t;
//Do some operation
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…