【发布时间】:2019-05-27 09:28:32
【问题描述】:
我想将实现隐式转换为接口。我知道 C# 规范不允许这样做,这对我的用例来说很好。
但是当我隐式转换为实现接口的类型时,我无法将其存储在该接口的变量中。这让我很惊讶。
这些是定义:
public interface ISomeInterface
{
}
public class SomeImplementation : ISomeInterface
{
}
public class Class1
{
public static implicit operator SomeImplementation(Class1 class1)
{
return new SomeImplementation();
}
}
var class1 = new Class1();
// Works
SomeImplementation s1 = class1;
// Works
ISomeInterface i1 = s1;
// This is what I want to do
ISomeInterface i2 = class1;
// Cannot implicitly convert type 'Class1' to 'ISomeInterface'.
// An explicit conversion exists (are you missing a cast?)
我希望它能够编译,因为可以将 Class1 隐式转换为 SomeImplementation 和 SomeImplementation 实现 ISomeInterface。
为什么不允许这样做?
【问题讨论】:
标签: c# compiler-errors implicit-conversion