c# - 如何获取具有指定名称的 DataMemberAttribute 的属性?

标签 c# .net reflection properties propertyinfo

我如何反射性地获取具有给定名称的 DataMember 的属性(让我们假设每个 DataMember 都有一个唯一的名称)?例如,在以下代码中,具有名称“p1”的 DataMember 的属性是 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; }
}

目前,我有:

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

这行得通,但感觉还可以改进。我特别不喜欢 GetCustomAttributes() 被调用了两次。

如何重写更好?理想情况下,如果我能将它做成一个简单的单行代码,那就太好了。

最佳答案

// 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");

注意事项:

  • Attribute.IsDefined用于在不检索其数据的情况下检查自定义属性是否存在。因此它比 Attribute.GetCustomAttribute 更高效,并且用于在第一步中跳过属性。

  • Where 运算符之后,我们剩下的属性正好是一个 DataMemberAttribute:没有此属性的属性已被过滤out,并且不能多次应用。因此我们可以使用 Attribute.GetCustomAttribute 而不是 Attribute.GetCustomAttributes

关于c# - 如何获取具有指定名称的 DataMemberAttribute 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14671507/

相关文章:

.net - MEF 与 Mono.AddIn

reflection - 使用反射的 F# 通用 Map.count

c# - 当 T 未知时,如何使用反射执行 List<object>.Cast<T>

c# - 使用NEST API进行日期范围搜索以进行 Elasticsearch ,返回不适当的结果

c# - 未设置时属性是否始终具有值?

c# - 类型直接或间接取决于自身 Simple Injector

c# - C#中如何判断组合框中的项目是否被选中?

.net - 如何不为种子实体设置 DatabaseGenerateOption.Identity

java - forName 和 Class.forName 和 isInstance 的使用

c# - 使用Transaction Scop时重置隔离级别