给定以下结构:
public struct Foo<T>
{
public Foo(T obj) { }
public static implicit operator Foo<T>(T input)
{
return new Foo<T>(input);
}
}
Run Code Online (Sandbox Code Playgroud)
此代码编译:
private Foo<ICloneable> MakeFoo()
{
string c = "hello";
return c; // Success: string is ICloneable, ICloneable implicitly converted to Foo<ICloneable>
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码没有编译 - 为什么?
private Foo<ICloneable> MakeFoo()
{
ICloneable c = "hello";
return c; // Error: ICloneable can't be converted to Foo<ICloneable>. WTH?
}
Run Code Online (Sandbox Code Playgroud) 说,我有一个界面
public interface ISomeControl
{
Control MyControl { get; }
...
}
Run Code Online (Sandbox Code Playgroud)
是否可以像这样定义smth:
public static implicit operator Control(ISomeControl ctrl)
{
return ctrl.MyControl;
}
Run Code Online (Sandbox Code Playgroud)
或者更确切地说,为什么我不能在C#中这样做?