我已经阅读了一些关于Design-Time Attributes for Components的内容。在那里,我找到了一个名为CategoryAttribute的属性。在那个页面上它说
CategoryAttribute类定义以下常见类别:
然后列出一些常见的类别。其中一个是例如Appearance。我想,太棒了!然后我可以使用[Category.Appearance]
代替[Category("Appearance")]
!但显然我不能?试图写它,但Intellisense不会接受它,它不会编译。我在这里错过了什么吗?是不是这些属性不适合?如果没有,它们是为了什么?如果是,我该如何使用它们?
是的,我确实有using
来访问CategoryAttribute
,因为[Category("Whatever")]
可以正常工作。我只是想知道如何使用这些定义的常见类别。
答案 0 :(得分:4)
正如你在MSDN上看到的,它只是一个getter属性,而不是一个setter。
public static CategoryAttribute Appearance { get; }
实际上,这是使用Reflector的代码:
public static CategoryAttribute Appearance
{
get
{
if (appearance == null)
{
appearance = new CategoryAttribute("Appearance");
}
return appearance;
}
}
所以它没有做太多。
我能看到的唯一用途就是这样:
foreach (CategoryAttribute attrib in prop.GetCustomAttributes(typeof(CategoryAttribute), false))
{
bool result = attrib.Equals(CategoryAttribute.Appearance);
}
基本上,当使用反射来查看类时,您可以轻松地检查它属于哪个类别,而无需进行字符串比较。但是你不能以你想要的方式使用它。
答案 1 :(得分:2)
通过CategoryAttribute.Appearance访问静态属性。但属性系统不允许您在属性声明中调用代码,我想这就是为什么它不会为您编译。你可能不得不满足于[类别(“外观”)]。