假设我有一个最小的 C# 类,如下所示:
class Thing
{
private float a, b, c, d;
(...)
}
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以将一个属性应用到所有四个字段而不必写四次?如果我放在[SomeAttribute]前面private,它似乎a只适用于。
class Thing
{
[SomeAttribute]
public float a, b, c, d;
}
Run Code Online (Sandbox Code Playgroud)
您提出的上述内容将按照您期望的方式工作。你可以测试这个:
[AttributeUsage(AttributeTargets.Field)]
sealed class SomeAttribute: Attribute
{
public SomeAttribute()
{
}
}
class Program
{
static void Main(string[] args)
{
var t = typeof(Thing);
var attrs = from f in t.GetFields()
from a in f.GetCustomAttributes()
select new { Name = f.Name, Attribute = a.GetType() };
foreach (var a in attrs)
Console.WriteLine(a.Name + ": " + a.Attribute);
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
它打印:
a:一些属性 b: 一些属性 c: 某些属性 d:某些属性
| 归档时间: |
|
| 查看次数: |
740 次 |
| 最近记录: |