假设我有以下类型:
为什么我不能写这个?
但是仍然允许写这个吗?
我遇到了这个错误:
无法隐式转换类型IBar为Foo。存在一个显式转换(你是否缺少一次强制类型转换?)。
我知道在接口中不能使用隐式操作符,但为什么在接口作为泛型参数时也不能使用它们?
public class Foo<T>
{
public Foo(T value)
{
Value = value;
}
public T Value {get;set;}
public static implicit operator Foo<T>(T t)
{
return new Foo<T>(t);
}
}
public interface IBar
{
}
public class Bar : IBar
{
}
为什么我不能写这个?
Foo<IBar> foo = (IBar)new Bar();
但是仍然允许写这个吗?
Foo<Bar> foo = new Bar();
我遇到了这个错误:
无法隐式转换类型IBar为Foo。存在一个显式转换(你是否缺少一次强制类型转换?)。
我知道在接口中不能使用隐式操作符,但为什么在接口作为泛型参数时也不能使用它们?
(IBar)
的情况下工作。 - IS4public static Foo<T> ToFoo<T>(this T t)
? - Jon Skeet