问题
I'm struggling with how to properly use C# Generics. Specifically, I want to have a method that takes a Generic Type as a parameter and does different things based on the type of the Generic. But, I cannot "downcast" the Generic Type. See example below.
Compiler complains about the cast (Bar<Foo>)
saying "Cannot convert type Bar<T>
to Bar<Foo>
". But at runtime the cast is OK since I've checked the type.
public class Foo { }
public class Bar<T> { }
// wraps a Bar of generic type Foo
public class FooBar<T> where T : Foo
{
Bar<T> bar;
public FooBar(Bar<T> bar)
{
this.bar = bar;
}
}
public class Thing
{
public object getTheRightType<T>(Bar<T> bar)
{
if (typeof(T) == typeof(Foo))
{
return new FooBar<Foo>( (Bar<Foo>) bar); // won't compile cast
}
else
{
return bar;
}
}
}
回答1:
The compiler can't know that Bar<T>
can be cast to Bar<Foo>
in this case, because it's not generally true. You have to "cheat" by introducing a cast to object
in between:
return new FooBar<Foo>( (Bar<Foo>)(object) bar);
回答2:
This should do the trick, and you won't have to cast to object
first.
public class Thing
{
public object getTheRightType<T>(Bar<T> bar)
{
if (typeof(T) == typeof(Foo))
{
return new FooBar<Foo>(bar as Bar<Foo>); // will compile cast
}
else
{
return bar;
}
}
}
来源:https://stackoverflow.com/questions/13144902/how-to-downcast-an-instance-of-a-generic-type