【问题标题】:Why constant defined in an interface cannot be accessed without Interface name in the implemented class?为什么在实现的类中没有接口名称就不能访问接口中定义的常量?
【发布时间】:2021-07-14 09:55:44
【问题描述】:

我们有接口和实现类:

pubic interface IStackContainer {
    const string DefaultStack = "default";
}

public class StackContainer<T> : MyBaseStackContainer<T>, IStackContainer{
    protected  internal string Stack {
        get { return Get(nameof(Stack), IInterface.DefaultStack); } //works fine
        set { Set(nameof(Stack), DefaultStack, value); }   //doesn't exist in the current context, why?
    }
}

为什么我不能在没有“IInterface”的情况下访问 StackContainer 中的常量?

PS:我在这里的目的是将 const 放置在某个地方而不是 StackContainer 以便于访问它。 如果它是在 StackContainer 中定义的,我可以像这样使用它:StackContainer.DefaultStack,但我认为这不是一个好的决定。

【问题讨论】:

  • 这些类不是从另一个继承的。在我的情况下,如果 IStackContainer 是一个类,它会正常工作
  • @Progman 这是另一个问题,不相关
  • 虽然是同样的规则——如果你想在 any 其他类型中引用一个常量,无论可能存在什么继承/实现关系,你总是必须通过类型名称引用它。
  • @Damien_The_Unbeliever ...除非它在基类中。由于基类类似于接口,因此期望它们在此处的行为方式相同并非没有道理
  • 好吧,如果你想从 public 接口“继承”,你需要等待几个月才能安全地访问任何常量成员!

标签: c# constants c#-8.0 default-interface-member


【解决方案1】:

琐碎,因为这是规范所说的。

我怀疑这是为了避免多重继承带来的问题。考虑:

interface IA
{
    public const string DefaultStack = "default";
}

interface IB
{
}

class C : IA, IB
{
}

// Imagine this is allowed:
string stack = C.DefaultStack;

想象一下,即使 IAIB 在不同的程序集中。

现在将const string DefaultStack = "..." 添加到IB 是一项重大更改,因为这会使C.DefaultStack 产生歧义。这实际上意味着向接口添加 any const 字段是一项重大更改,因为这可能会与某个其他接口中的同名字段发生冲突,并且会破坏在某处实现这两个接口的某种类型.

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2011-08-18
    • 2017-08-07
    • 1970-01-01
    • 2021-07-20
    • 2018-10-24
    相关资源
    最近更新 更多