Suppose I have a minimal C# class that looks like the following:
class Thing
{
private float a, b, c, d;
(...)
}
Is there a way that I can apply an attribute to all four fields without having to write it out four times? If I put [SomeAttribute]
in front of the private
, it appears to apply to a
only.
class Thing
{
[SomeAttribute]
public float a, b, c, d;
}
The above, which you proposed, would work how you expect it to work. You can test this:
[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();
}
}
It prints:
a: SomeAttribute b: SomeAttribute c: SomeAttribute d: SomeAttribute
Yes, it's possible:
[SomeAttribute]
public int m_nVar1, m_nVar2;
(but obviously only if the types are the same)
REFERENCE
Example:
[ContextStatic]
private float a, b, c, d;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With