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

sta*_*ica 6 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."
Run Code Online (Sandbox Code Playgroud)

注意:如果class XY : IX和,将发生相同的错误where T : IX.不过,我已经选择了一个更复杂的例子,因为一个简单的一个可能引发circumventive答案,如,"只要改变的类型xyTIX",这不会回答为什么这个转换失败.

Eri*_*ert 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.
Run Code Online (Sandbox Code Playgroud)


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

  • @stakx:我怀疑你是在错误的方向推理.约束意味着*任何T都可以转换为给定的接口类型*,而不是*实现此接口的任何东西都可以转换为T*. (5认同)