CategoryAttribute返回"杂项"对于名为&#34的类别;默认"

时间:2017-02-04 11:50:23

标签: c# .net winforms attributes system.componentmodel

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

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

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

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;
           }
       }
   }
}

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

我的问题是,为什么" Misc"当"默认"时返回被设置为类别。

此致

Amal Raj

1 个答案:

答案 0 :(得分:1)

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

PropertyCategoryDefault = Misc

您还会收到ConfigDragDropWindowStyle的其他文字:

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
}