如何向下转换Generic类型的实例?

Mar*_*sen 1 c# generics casting type-conversion

我正在努力如何正确使用C#Generics.具体来说,我希望有一个方法,它将Generic Type作为参数,并根据Generic的类型执行不同的操作.但是,我不能"低估"通用类型.见下面的例子.

编译器抱怨演员(Bar<Foo>)说"无法将类型转换Bar<T>Bar<Foo>".但是在运行时,演员阵容很好,因为我已经检查了类型.

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 7

在这种情况下,编译器无法知道Bar<T>可以转换为Bar<Foo>,因为它通常不是真的.你必须通过object在两者之间引入一个演员来"欺骗" :

return new FooBar<Foo>( (Bar<Foo>)(object) bar);
Run Code Online (Sandbox Code Playgroud)