如何向下转换泛型类型的实例? [英] How to downcast an instance of a Generic type?

查看:239
本文介绍了如何向下转换泛型类型的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力如何正确使用C#泛型。具体来说,我想有一个方法将Generic Type作为参数,并根据Generic的类型做不同的事情。但是,我不能贬低泛型。看看下面的例子。

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.

编译器抱怨转换(Bar< Foo>)Can not convert type Bar< T> Bar< Foo> 。但是在运行时,由于已经检查过类型,所以转换是OK的。

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;
        }
    }
}


推荐答案

编译器无法知道 Bar< T> 可以转换成 Bar< Foo> in这种情况,因为这通常不是真的。您必须通过在对象之间引入转换来欺骗:

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);

这篇关于如何向下转换泛型类型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆