对多个字段应用c#属性

本文关键字:属性 应用 字段 | 更新日期: 2023-09-27 18:10:44

假设我有一个最小的c#类,如下所示:

class Thing
{
    private float a, b, c, d;
    (...)
}

是否有一种方法,我可以应用一个属性到所有四个字段,而不必写出来四次?如果我把[SomeAttribute]放在private前面,它似乎只适用于a

对多个字段应用c#属性

class Thing
{
    [SomeAttribute]
    public float a, b, c, d;
}

你所建议的上述内容将按照你所期望的方式工作。你可以测试一下:

[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();
    }
}

它打印:<>之前答:SomeAttributeb: SomeAttributec: SomeAttributed: SomeAttribute

是有可能的:

[SomeAttribute]
public int m_nVar1, m_nVar2;

(但显然只有当类型相同时)

参考

的例子:

[ContextStatic]
private float a, b, c, d;

我认为使用visual studio无论如何都无法做到这一点。

我能想到的最不烦人的方法是使用MultiEdit,您可以放置多个光标,并且只写一次属性。