Eug*_*mov 1 c# constants c#-8.0 default-interface-member
我们有接口和实现类:
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?
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我不能在没有“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;
Run Code Online (Sandbox Code Playgroud)
甚至想象一下,IA并且IB在不同的程序集中。
现在添加const string DefaultStack = "..."到是一个突破性的变化IB,因为这会变得C.DefaultStack模棱两可。这实际上意味着向接口添加任何const 字段都是一个重大更改,因为这可能会与其他接口中的同名字段冲突,并且会破坏在某处实现这两个接口的某些类型。