How to get the property that has a DataMemberAttri

2019-06-19 18:10发布

How can I reflectively get the property that has the DataMember with a given name (let's assume every DataMember has a unique name)? For example, in the following code the property with the DataMember that has name "p1" is PropertyOne:

[DataContract(Name = "MyContract")]
public class MyContract
{
    [DataMember(Name = "p1")]
    public string PropertyOne { get; set; }

    [DataMember(Name = "p2")]
    public string PropertyTwo { get; set; }

    [DataMember(Name = "p3")]
    public string PropertyThree { get; set; }
}

Currently, I have:

string dataMemberName = ...;

var dataMemberProperties = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(DataMemberAttribute), false).Any());

var propInfo = dataMemberProperties.Where(p => ((DataMemberAttribute)p.GetCustomAttributes(typeof(DataMemberAttribute), false).First()).Name == dataMemberName).FirstOrDefault();

This works, but it feels like it could be improved. I particularly don't like that GetCustomAttributes() is called twice.

How can it be re-written better? Ideally, it would be great if I could make it a simple one-liner.

4条回答
叼着烟拽天下
2楼-- · 2019-06-19 18:43

You could use LINQ:

string dataMemberName = ...;
var propInfo =
    (from property in typeof(T).GetProperties()
    let attributes = property
        .GetCustomAttributes(typeof(DataMemberAttribute), false)
        .OfType<DataMemberAttribute>()
    where attributes.Any(a => a.Name == dataMemberName)
    select property).FirstOrDefault();

or if you prefer:

string dataMemberName = ...;
var propInfo = typeof(T)
    .GetProperties()
    .Where(p => p
        .GetCustomAttributes(typeof(DataMemberAttribute), false)
        .OfType<DataMemberAttribute>()
        .Any(x => x.Name == dataMemberName)
    )
    .FirstOrDefault();
查看更多
手持菜刀,她持情操
3楼-- · 2019-06-19 18:44

I needed to get the value of the property and not the property itself so used Darin Dimitrov's answer but added .GetValue(this) to the end to return the value instead.

Here is what my class ended up looking like:

[DataContract]
public class Item
{
    [DataMember(Name = "kpiId")]
    public string KPIId { get; set; }
    [DataMember(Name = "value")]
    public string Value { get; set; }
    [DataMember(Name = "unit")]
    public string Unit{ get; set; }
    [DataMember(Name = "status")]
    public string Status { get; set; }
    [DataMember(Name = "category")]
    public string Category { get; set; }
    [DataMember(Name = "description")]
    public string Description { get; set; }
    [DataMember(Name = "source")]
    public string Source { get; set; }
    [DataMember(Name = "messages")]
    public SysMessage[] Messages { get; set; }

    public object getDataMemberByName(string name)
    {
         return (typeof(Item).GetProperties().FirstOrDefault(p => p.GetCustomAttributes(typeof(DataMemberAttribute), false)
                              .OfType<DataMemberAttribute>()
                              .Any(x => x.Name == name))).GetValue(this);
    }
}
查看更多
爷、活的狠高调
4楼-- · 2019-06-19 19:01
// using System.Linq;
// using System.Reflection;
// using System.Runtime.Serialization;
obj.GetType()
   .GetProperties(…)
   .Where(p => Attribute.IsDefined(p, typeof(DataMemberAttribute)))
   .Single(p => ((DataMemberAttribute)Attribute.GetCustomAttribute(
                    p, typeof(DataMemberAttribute))).Name == "Foo");

Notes:

  • Attribute.IsDefined is used to check for the presence of a custom attribute without retrieving its data. Thus it is more efficient than Attribute.GetCustomAttribute and used to skip properties in a first step.

  • After the Where operator, we are left with properties that have exactly one DataMemberAttribute: Properties without this attribute have been filtered out, and it cannot be applied more than once. Therefore we can use Attribute.GetCustomAttribute instead of Attribute.GetCustomAttributes.

查看更多
萌系小妹纸
5楼-- · 2019-06-19 19:07

You could use Fasterflect to make your reflection code simpler and easier on the eyes:

var property = typeof(T).MembersAndAttributes( MemberTypes.Property, typeof(DataMemberAttribute) )
    .Where( ma => ma.Attributes.First().Name == dataMemberName )
    .Select( ma => ma.Member as PropertyInfo )
    .FirstOrDefault();

If you only need to check for the presence of the attribute, something like this could be used instead:

var property = typeof(T).PropertiesWith<DataMemberAttribute>( Flags.InstancePublic )
    .Where( p => p.Name == dataMemberName ).FirstOrDefault();

Fasterflect comes with a nice set of extension methods and includes some neat performance optimizations using IL generation if you also need speed.

查看更多
登录 后发表回答