简体   繁体   English

私有const在类级别定义,然后在属性上使用,为什么要编译?

[英]Private const defined on class level and then used on an attribute, why this compile?

Have a look at the following code: 看下面的代码:

public class Person
{
    private const string MyConst = "SomeValue";

    [MyAttribute(MyConst)]
    public string Name {get;set;}
}

MyConst is defined as private and in my opinion it should not be accessible for MyAttribute. MyConst被定义为private ,我认为MyAttribute应该不可访问。 However this code compiles well. 但是,此代码编译良好。

Anyone knows the reason? 有人知道原因吗?

Private members are only accessible within the same class body as where they're declared. 私有成员只能在与其声明的地方相同的类体内访问。 I guess it's accessible because you're declaring and using it in the same class. 我猜它是可访问的,因为您在同一个类中声明和使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么不能在类级别使用'NonSerialized'属性?如何防止类的序列化? - Why can't the 'NonSerialized' attribute be used at the class level? How to prevent serialization of a class? 为什么可以从属性访问私有const字段? - Why it is possible to access private const field from attribute? 如何从程序集级属性引用私有类的类型? - How to reference the type of a private class from an assembly-level attribute? 为什么 C# 不支持 class / 方法级别的 const? - Why doesn't C# support const on a class / method level? 类级别是否有Conditional属性? - Is there a Conditional attribute at the class level? 私有类中的属性访问级别 - Access level of property in Private Class 类级别的可本地化的DisplayName属性 - Localizable DisplayName attribute for class level 从属性中的基类访问受保护的const - Access protected const from base class in attribute 私有类级变量是否继承? - Are private class-level variables inherited? C# 接口和类。 接口中需要的类中使用的变量不能是私有的,或者私有的只能是公共的。 为什么? - C# Interfaces and classes. Variables used in the class needed in the interface can't be private, or private only public. Why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM