【问题标题】:Storing the result of an implicit cast to a concrete type into an interface fails将隐式强制转换的结果存储到接口中失败
【发布时间】: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 隐式转换为 SomeImplementationSomeImplementation 实现 ISomeInterface

为什么不允许这样做?

【问题讨论】:

    标签: c# compiler-errors implicit-conversion


    【解决方案1】:

    “嗯,简而言之,不允许从/到接口的自己的转换没有技术原因。原因是因为它们打开了语言设计者不想打开的某些场景的大门,为此他们禁止他们的原因。” - 详情请见Conversions (explicit or implicit) and interfaces in C#

    【讨论】:

    • 那么也是“设计”。微软应该庆幸我没有加入他们的语言设计团队。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2014-01-16
    • 2013-04-17
    • 2015-10-20
    • 2023-03-10
    相关资源
    最近更新 更多