2

我有一个名为的类CommonKeys.cs,它包含如下属性,

public class Test
{
   private SolidBrush _backgroundbrush;
   [CategoryAttribute("Default")]
   public SolidBrush BackgroundBrush
   {
       get
       {
           return this._backgroundbrush;
       }
       set
       {
           this._backgroundbrush = value;
       }
   }
}

当我使用以下代码访问上述属性及其类别时,它将“杂项”作为类别返回,而不是原始类别“默认”。

public static void GetCategoryName()
{
   PropertyInfo[] Props = typeof(Test).GetProperties(BindingFlags.Public | BindingFlags.Instance);
   foreach (PropertyInfo prop in Props)
   {
       var attributes = prop.GetCustomAttributes(false);
       string categoryName = String.Empty;
       foreach (var attr in attributes)
       {
           if (attr is CategoryAttribute)
           {
               categoryName = (attr as CategoryAttribute).Category;
           }
       }
   }
}

但是当我更改“默认”以外的类别名称时,它会返回确切的类别名称。

我的问题是,为什么当“默认”设置为类别时返回“杂项”。

问候,

阿迈勒·拉吉

4

1 回答 1

2

这是因为CategoryAttribute类的实现。对于某些值,它从 .net 框架的字符串资源中获取类别名称。这些值中的Default一个是这样定义的:

PropertyCategoryDefault = Misc

您还将收到另一个文本Config,DragDropWindowStyle:

PropertyCategoryConfig = Configurations
PropertyCategoryDragDrop = Drag Drop
PropertyCategoryWindowStyle = Window Style

以下是相关的实现:

public string Category {
    get {
        if (!localized) {
            localized = true;
            string localizedValue = GetLocalizedString(categoryValue);
            if (localizedValue != null) {
                categoryValue = localizedValue;
            }
        }
        return categoryValue;
    }
}
protected virtual string GetLocalizedString(string value) {
#if !SILVERLIGHT
    return (string)SR.GetObject("PropertyCategory" + value);
#else
    bool usedFallback;
    string localizedString = SR.GetString("PropertyCategory" + value, out usedFallback);
    if (usedFallback) {
        return null;
    }
    return localizedString;
#endif
}
于 2017-02-04T18:21:19.840 回答