How to get the property that has a DataMemberAttribute with a specified name?

喜你入骨 提交于 2020-01-14 08:03:12

问题


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.


回答1:


// 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.




回答2:


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:


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.




回答4:


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);
    }
}


来源:https://stackoverflow.com/questions/14671507/how-to-get-the-property-that-has-a-datamemberattribute-with-a-specified-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!