Hello!
Does anybody know how do I define an attribute for a property Like this:
public class Test {[myproperty's attribute - how to define it ]
private string MyProperty;
}
After defining it, I should use it via Reflection. Will it be shown in Attributes collection of PropertyInfo class
Thanks!

Define attributes for a property
Mikkel Haugstrup Jensen
You create a class derived from System.Attribute, add the AttributeUsage attribute to it and make sure it includes AttributeTargets.Property.
Once you've applied the attribute it will indeed show up in PropertyInfo.Attributes.
George2
A property has a get and/or set accessor, like the MyProperty in my example. The _myField should be returned by GetFields, and MyProperty by GetProperties. What string are you talking about
Neotech
First off, in your example, you're using a field, not a property. so FieldInfo would be the correct usage. Secondly, no it will not appear in PropertyInfo.Attributes or in FieldInfo.Attributes, but will appear in PropertyInfo.GetCustomAttributes or FieldInfo.GetCustomAttributes, depending on whihc one you choose. Note that many Reflection items implement ICustomAttributeProvider, which gives access to this GetCustomAttributes method.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class MyAttribute : Attribute
{
}
public class MyClass
{
[MyAttribute]
private string _myField = null;
[MyAttribute]
public string MyProperty
{
get { return _myField; }
}
}
programmer01
Thanks!
But the string is returned from GetProperties(), not from GetFields()... i didn’t understand their differences from documentation.
Jianxing
Sean,
Thanks... it wasnt too clear for me.