这是为什么合法的吗?指的是恒定的类型,从属性*月*的类型,而不与类型名称prefixing? [英] Why is this legal? Referring to a constant in a type, from an attribute *on* the type, without prefixing with type name?
问题描述
请看下面 LINQPad 计划:
void Main() { }
[TestAttribute(Name)]
public class Test
{
public const string Name = "Test";
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
[Serializable]
public class TestAttribute : Attribute
{
public TestAttribute(string dummy)
{
}
}
这编译顺利。为什么呢?
This compiles without a hitch. Why?
具体做法是:
[TestAttribute(Name)]
public class Test
{
public const string Name = "Test";
我为什么不都这样写:
Why don't I have to write this:
vvvvv
[TestAttribute(Test.Name)]
public class Test
{
public const string Name = "Test";
被认为是内部的类型,因而在范围属性声明?
Is the attribute declaration deemed to be "inside" the type, and thus in scope?
推荐答案
的属性实例声明的范围确实是在其上附着,或类型的(在一个方法,参数等的情况下)含有在其上附着的元件的类型。
The scope of an attribute instance declaration is indeed that of the type on which it is attached, or (in the case of a method, parameter, etc.) the type containing the element on which it is attached.
我找不到具体的上的东西,虽然标准的确说:
I can't find anything specific on that, though the standard does say:
属性可以在全局范围指定(指定的装配包含属性)和类型声明(§16.6),类成员声明(§17.1.4),结构成员声明(第18.2节) ,接口成员声明(§20.2),枚举成员声明(§21.1),访问器声明(§17.6.2),事件访问器声明(§17.7),形式参数数组中的元素(§ 17.5.1),和类型参数数组中的元素(§25.1.1)。
Attributes can be specified at global scope (to specify attributes on the containing assembly) and for type-declarations (§16.6), class-member-declarations (§17.1.4), struct-member-declarations (§18.2), interface-member-declarations (§20.2), enum-member-declarations (§21.1), accessor-declarations (§17.6.2), event-accessor-declarations (§17.7), elements of formal-parameter-lists (§17.5.1), and elements of type-parameter-lists (§25.1.1).
虽然它没有明确说的类范围内任何东西,它不区分在全球范围内全局属性的范围较广。
While it doesn't explicitly say anything about class scope, it does differentiate that from the wider scope of global attributes in "global scope".
我注意到,您的类CIL是:
I'd note that the CIL of your class would be:
class public auto ansi beforefieldinit SomeNamespace.Test extends [mscorlib]System.Object
{
.custom instance void SomeNamespace.TestAttribute::.ctor(string) = (
01 00 04 54 65 73 74 00 00
)
.field public static literal string Name = "Test"
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
.maxstack 8
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
在CIL作用域比C#
这篇关于这是为什么合法的吗?指的是恒定的类型,从属性*月*的类型,而不与类型名称prefixing?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!