Reputation: 285
I have created a custom attribute & used it in properties (not fields) of my class.
When i call FormatterServices.GetSerializableMembers, it does give me all the properties
But when i try to read the attribute using MemberInfo.GetCustomAttributes, it doesnt give me any value.
When i try to achieve the same using object.GetType().GetProperties().GetCustomAttributes, It works perfectly.
Any idea why it is not giving the information in MemberInfo?
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute { }
//DOES NOT WORK
MemberInfo[] members = FormatterServices.GetSerializableMembers(recordObject.GetType());
object[] attributes = members[0].GetCustomAttributes(typeof(MyAttribute), false)
//WORKS
PropertyInfo[] properties = recordObject.GetType().GetProperties();
object[] attributes = properties[0].GetCustomAttributes(typeof(MyAttribute), false);
Upvotes: 0
Views: 815
Reputation: 5602
FormatterServices.GetSerializableMembers
does not return any properties but rather fields of the serializable class.
So for instance of the following sample class:
[Serializable]
public class TestClass
{
private int _test;
[MyAttribute]
public int Test
{
get { return _test; }
set { _test = value; }
}
}
FormatterServices.GetSerializableMembers
with get use MemberInfo
of _test
field, but GetType().GetProperties() with return MemberInfo
of the property.
And because the field itself doesn't have any attributes attached to it therefore GetCustomAttributes
won't return anything.
Upvotes: 2
Reputation: 6570
Most likely, the first member returned in
FormatterServices.GetSerializableMembers(recordObject.GetType());
is not actually the property you expected.
Upvotes: 1