I am trying to find the DataMember attribute on properties of a class. I can find the attribute if it is on a property defined directly in the class. However if the property is defined in a base class and overridden, the attribute is not found. I have found several links stating you have to use System.Attribute to get this information. Below is a direct quote from Microsoft.
Calling ICustomAttributeProvider.GetCustomAttributes on PropertyInfo or EventInfo when the inherit parameter of GetCustomAttributes is true does not walk the type hierarchy. Use System.Attribute to inherit custom attributes.
This seems to fix the problem completely when using the full framework. This seems to fix the problem for ONLY “non-system” attributes in Silverlight (tested on Silverlight 3.0, 4.0, 5.0). My sample code below shows that DataMemberAttribute is not returned while another custom defined Attribute is returned. Is this a bug or am I missing something?
public class CustomAttribute : Attribute
{
}
public class Animal
{
[DataMember(), CustomAttribute()]
public virtual decimal Weight { get; set; }
}
public class Dog : Animal
{
public override decimal Weight { get; set; }
}
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
var animalAttributes = Attribute.GetCustomAttributes(typeof(Animal).GetProperties()[0], true);
var dogAttributes = Attribute.GetCustomAttributes(typeof(Dog).GetProperties()[0], true);
//animalAttributes contains 2 entries (DataMember, CustomAttribute)
//dogAttributes contains only 1 entry (CustomAttribute)
}
}
I think you have to set the AttributeUsage in you CustomAttribute to accept inheritance: http://msdn.microsoft.com/en-us/library/2ab31zeh.aspx
Set the Inherited in AttributeUsage to true.
EDITED
The DataMemberAttribute, does not allows inheritance. http://msdn.microsoft.com/pt-br/library/system.runtime.serialization.datamemberattribute.aspx