为什么list.Add(new B())
编译list.Add(new Wrapper<B>())
而不编译?我认为要么两者都编译,要么都不编译,因为我认为编译器能够找出B
返回的隐式转换 aWrapper<B>
与new Wrapper<B>()
. 我在 VS 2012 中使用 C# 4。
class Wrapper<T> where T : new()
{
public static implicit operator Wrapper<T>(T obj)
{
return new Wrapper<T>();
}
public static implicit operator T(Wrapper<T> obj)
{
return new T();
}
}
class A { }
class B : A { }
class MyClass
{
public static void Main(string[] args)
{
List<Wrapper<A>> list = new List<Wrapper<A>>();
//This line compiles and runs successfully
list.Add(new B());
//This line doesn't compile
list.Add(new Wrapper<B>());
}
}