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

use*_*173 74 c# reflection

我有班级和财产.一些属性可以标记属性(它是我的LocalizedDisplayName继承DisplayNameAttribute).这是获取类的所有属性的方法:

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

我想在列表框中添加类的属性,在列表框中标记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);
        }
    }  
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 119

它可能最容易使用IsDefined:

var properties = type.GetProperties()
    .Where(prop => prop.IsDefined(typeof(LocalizedDisplayNameAttribute), false));
Run Code Online (Sandbox Code Playgroud)

编辑:要获得自己的价值,你可以使用:

var attributes = (LocalizedDisplayNameAttribute[]) 
      prop.GetCustomAttributes(typeof(LocalizedDisplayNameAttribute), false);
Run Code Online (Sandbox Code Playgroud)

  • +1; Nit-pick:我会指定`IEnumerable <PropertyInfo>`这里:)如果看到这个答案的人不熟悉Linq或Reflections,会很有帮助. (5认同)