为什么不允许从“A类:IX”转换为通用“T T:IX”?

时间:2012-02-24 19:05:56

标签: c# generics type-conversion type-constraints

为什么以下会导致编译错误?

interface IX {}
interface IY {}
class XY : IX, IY {}

void Foo<T>() where T : IX, IY
{
    T xy = new XY();
    …   // ^^^^^^^^
}       // error: "Implicit conversion of type 'XY' to 'T' is not possible."

注意:如果class XY : IXwhere T : IX,则会出现同样的错误。但是,我选择了一个更复杂的例子,因为一个更简单的例子可能会引发一些有用的答案,例如,“只需将xy的类型从T更改为IX,它不会回答为什么此转换失败。

2 个答案:

答案 0 :(得分:15)

因为如果这是合法的,那么你可以这样做:

interface IPet {} 
interface IMammal {} 
class Dog : IPet, IMammal {}  
class Cat : IPet, IMammal {}
T Foo<T>() where T : IPet, IMammal
{     
  return new Dog();
}
...
Cat cat = Foo<Cat>();  // Assigns a Dog to a variable of type Cat.

答案 1 :(得分:12)

鉴于class ABC : IX, IY { }Foo<ABC>,您希望能够使用new XY()吗?因为你不应该有这种期望。编译器也不会。

T并不总是XY。 T将是ABC,DEF或其他任何,可以实现您的两个接口,从而满足您的约束。 XY不能转换为ABC,DEF或 T 的任何无限可能性,因此您有错误消息:无法将XY隐式转换为T.

只有new T()才有合法性,如果方法受限于支持,那么这只是

void Foo<T>() where T : IX, IY, new()
{
    T obj = new T();
}
相关问题