获取标记某些属性的所有属性

时间:2011-09-05 08:53:07

标签: c# reflection

我有类和属性。某些属性可以标记为属性(我的LocalizedDisplayName继承自DisplayNameAttribute)。 这是获取类的所有属性的方法:

private void FillAttribute()
{
    Type type = typeof (NormDoc);
    PropertyInfo[] propertyInfos = type.GetProperties();
    foreach (var propertyInfo in propertyInfos)
    {
        ...
    }
}

我想在列表框中添加标记为LocalizedDisplayName的类的属性,并在列表框中显示属性值。我怎么能这样做?

修改
这是LocalizedDisplayNameAttribute:

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
    {
        public LocalizedDisplayNameAttribute(string resourceId)
            : base(GetMessageFromResource(resourceId))
        { }

        private static string GetMessageFromResource(string resourceId)
        {
            var test =Thread.CurrentThread.CurrentCulture;
            ResourceManager manager = new ResourceManager("EArchive.Data.Resources.DataResource", Assembly.GetExecutingAssembly());
            return manager.GetString(resourceId);
        }
    }  

我想从资源文件中获取字符串。 感谢。

1 个答案:

答案 0 :(得分:113)

使用IsDefined可能最简单:

var properties = type.GetProperties()
    .Where(prop => prop.IsDefined(typeof(LocalizedDisplayNameAttribute), false));

编辑:要获取值本身,您可以使用:

var attributes = (LocalizedDisplayNameAttribute[]) 
      prop.GetCustomAttributes(typeof(LocalizedDisplayNameAttribute), false);
相关问题