是否有人知道是否可以在成员之后而不是之前声明属性,因为它通常显示在引用/代码示例中?
示例:
public class MarkerAttribute: Attribute
{
public MarkerAttribute(): base() { }
}
public class TheClass
{
public int PropertyWithNoAttribute1 { get; set; }
[Marker]
public int PropertyWithAttribute { get; set; }
public int PropertyWithNoAttribute2 { get; set; }
}
在这里,出于各种不感兴趣的原因,我想像这样代表同一个类(这相当于标准表示):
public class TheClass
{
public int PropertyWithNoAttribute1 { get; set; }
[Marker] public int PropertyWithAttribute { get; set; }
public int PropertyWithNoAttribute2 { get; set; }
}
有没有人知道是否有一些特殊的语法指示,以便可以像这样编写同一个类?
public class TheClass
{
public int PropertyWithNoAttribute1 { get; set; }
public int PropertyWithAttribute { get; set; } [Marker]
public int PropertyWithNoAttribute2 { get; set; }
}
我已经在以下计划中对此进行了测试,不幸的是它无法正常工作。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ScratchPad
{
public class MarkerAttribute: Attribute
{
public MarkerAttribute(): base() { }
}
public class TheClass
{
public int PropertyWithNoAttribute1 { get; set; }
public int PropertyWithAttribute { get; set; } [Marker]
public int PropertyWithNoAttribute2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
TheClass a = new TheClass();
System.Reflection.PropertyInfo PropertyWithNoAttribute1_Info = a.GetType().GetProperty("PropertyWithNoAttribute1");
System.Reflection.PropertyInfo PropertyWithAttribute_Info = a.GetType().GetProperty("PropertyWithAttribute");
System.Reflection.PropertyInfo PropertyWithNoAttribute2_Info = a.GetType().GetProperty("PropertyWithNoAttribute2");
object[] attributes = PropertyWithNoAttribute1_Info.GetCustomAttributes(typeof(MarkerAttribute), false);
if (attributes.Length > 0)
{
System.Console.WriteLine("{0} has attribute {1}", PropertyWithNoAttribute1_Info.Name, attributes[0].GetType().Name);
}
attributes = PropertyWithAttribute_Info.GetCustomAttributes(typeof(MarkerAttribute), false);
if (attributes.Length > 0)
{
System.Console.WriteLine("{0} has attribute {1}", PropertyWithAttribute_Info.Name, attributes[0].GetType().Name);
}
attributes = PropertyWithNoAttribute2_Info.GetCustomAttributes(typeof(MarkerAttribute), false);
if (attributes.Length > 0)
{
System.Console.WriteLine("{0} has attribute {1}", PropertyWithNoAttribute2_Info.Name, attributes[0].GetType().Name);
}
}
}
}
谢谢