How to downcast an instance of a Generic type?

邮差的信 提交于 2020-01-05 07:50:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!