c# - 在 C# 中转换受约束的泛型类

标签 c# generics casting

很简单,为什么这段代码编译失败?

public interface IWorld { }
public class Foo<T> where T : IWorld { }
public void Hello<T>(T t) where T : IWorld
{
    Foo<IWorld> bar1 = new Foo<T>(); //fails implicit cast
    Foo<IWorld> bar2 = (Foo<IWorld>)new Foo<T>(); //fails explicit cast
}

因为每个 T工具 IWorld , Foo<T> 的每个实例应该匹配 Foo<IWorld> .为什么不?有没有办法解决?我真的不想诉诸泛型来实现这一目标。

最佳答案

T : IWorld

表示 T 已经实现了 IWorld,并不意味着它仅实现了 IWorld 并且完全是 IWorld。它也可能已经实现了其他接口(interface)。

但是,C# 在其更高版本中支持此转换。请看http://msdn.microsoft.com/en-us/library/dd799517.aspx (泛型中的协变和逆变)

关于c# - 在 C# 中转换受约束的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13987961/

相关文章:

c# - ReaderWriterLockSlim 出错

swift - 数组中具有关联类型的协议(protocol) - 替代解决方案

java - 将 JNI 基本类型放入同一数组中

c - "Makes Pointer from Integer without a Cast"- 如何满足 GCC?

c# - 字符串从代码隐藏到 Javascript 中的数组

C# 从 DirectoryNotFoundException 获取目录名称

c++ - 对象没有命名类型 - C++

Java 泛型 : capture cannot be applied to Object

Java:为什么 "long"原始类型不接受简单数字?

c# - 为什么 SignedCms.ComputeSignature() 方法抛出 "Provider' s 公钥无效”异常?