尝试编译以下代码后:
public sealed class Program
{
[constructor: CLSCompliant(false)]
public Program()
{
}
}
我收到以下错误:
'constructor'不是公认的属性位置。此声明的有效属性位置为“方法”。此块中的所有属性将被忽略。 [Console.NET] csharp(CS0658)
我知道存在以下位置:assembly
,module
,method
,parameter
,return
等。因此,我的猜测是constructor
也应存在(因为我们也可以将构造函数作为属性的目标)。但似乎这里并非如此。
而且,我无法在MSDN上找到已识别属性位置的完整列表。因此,如果有人提供指向MSDN上位置列表的链接,这将很有帮助。
我对constructor
位置的猜测是基于我在通过CLR通过C#书中遇到以下代码示例之后的:
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
[assembly: CLSCompliant(true)]
[Serializable]
[DefaultMemberAttribute("Main")]
[DebuggerDisplayAttribute("Richter", Name = "Jeff", Target = typeof(Program))]
public sealed class Program
{
[Conditional("Debug")]
[Conditional("Release")]
public void DoSomething() { }
public Program()
{
}
[CLSCompliant(true)]
[STAThread]
public static void Main()
{
// Show the set of attributes applied to this type
ShowAttributes(typeof(Program));
// Get the set of methods associated with the type
var members =
from m in typeof(Program).GetTypeInfo().DeclaredMembers.OfType<MethodBase>()
where m.IsPublic
select m;
foreach (MemberInfo member in members)
{
// Show the set of attributes applied to this member
ShowAttributes(member);
}
}
private static void ShowAttributes(MemberInfo attributeTarget)
{
var attributes = attributeTarget.GetCustomAttributes<Attribute>();
Console.WriteLine("Attributes applied to {0}: {1}",
attributeTarget.Name, (attributes.Count() == 0 ? "None" : String.Empty));
foreach (Attribute attribute in attributes)
{
// Display the type of each applied attribute
Console.WriteLine(" {0}", attribute.GetType().ToString());
if (attribute is DefaultMemberAttribute)
Console.WriteLine(" MemberName={0}",
((DefaultMemberAttribute)attribute).MemberName);
if (attribute is ConditionalAttribute)
Console.WriteLine(" ConditionString={0}",
((ConditionalAttribute)attribute).ConditionString);
if (attribute is CLSCompliantAttribute)
Console.WriteLine(" IsCompliant={0}",
((CLSCompliantAttribute)attribute).IsCompliant);
DebuggerDisplayAttribute dda = attribute as DebuggerDisplayAttribute;
if (dda != null)
{
Console.WriteLine(" Value={0}, Name={1}, Target={2}",
dda.Value, dda.Name, dda.Target);
}
}
Console.WriteLine();
}
}
并且该程序的输出如下:
Attributes applied to Program:
System.SerializableAttribute
System.Diagnostics.DebuggerDisplayAttribute
Value=Richter, Name=Jeff, Target=Program
System.Reflection.DefaultMemberAttribute
MemberName=Main
Attributes applied to DoSomething:
System.Diagnostics.ConditionalAttribute
ConditionString=Release
System.Diagnostics.ConditionalAttribute
ConditionString=Debug
Attributes applied to Main:
System.CLSCompliantAttribute
IsCompliant=True
System.STAThreadAttribute
Attributes applied to .ctor: None
输出清楚表明,构造函数与类和方法的区别。并且由于存在位置class
和method
,因此我也希望constructor
位置也存在。
我仅出于学习目的需要它。