【问题标题】:Get all properties with values reflection获取所有具有值反射的属性
【发布时间】:2011-01-19 15:28:47
【问题描述】:

我编写了自定义属性属性并将其设置在我的类中的几个属性上。现在我想在运行时只获取具有此属性的属性,能够获取属性的值以及属性字段的值。你能帮我完成这个任务吗? 感谢您的帮助

【问题讨论】:

标签: c# .net reflection


【解决方案1】:

这是一个例子:

void Main()
{
    var myC = new C { Abc = "Hello!" };
    var t = typeof(C);
    foreach (var prop in t.GetProperties())
    {
        var attr = prop.GetCustomAttributes(typeof(StringLengthAttribute), true).Cast<StringLengthAttribute>().FirstOrDefault();
        if (attr != null)
        {
            var attrValue = attr.MaximumLength; // 100
            var propertyValue = prop.GetValue(myC, null); // "Hello!"
        }
    }
}
class C
{
    [StringLength(100)]
    public string Abc {get;set;}
}

【讨论】:

    【解决方案2】:

    您可以使用PropertyInfo.Attributes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-27
      • 2012-03-14
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      相关资源
      最近更新 更多