为什么在实现的类中没有接口名称就不能访问接口中定义的常量?

问题描述

我们有接口和实现类:

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,但我认为这不是一个好的决定。

解决方法

很简单,因为规范就是这么写的。

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

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 字段是一个重大更改,因为这可能会与其他接口中的同名字段冲突,并且会在某处破坏实现这两个接口的某些类型.