【发布时间】: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