4

我已经阅读了一些关于Design-Time Attributes for Components 的内容。在那里我找到了一个名为CategoryAttribute的属性。在那个页面上它说

CategoryAttribute 类定义了以下常见类别:

然后列出了一些常见的类别。其中之一是例如Appearance。我想,太棒了!然后我可以使用[Category.Appearance]而不是[Category("Appearance")]!但显然我不能?尝试编写它,但 Intellisense 无法接收它并且无法编译。我在这里错过了什么吗?难道这些属性不是为了这个吗?如果不是,它们是干什么用的?如果是,我该如何使用它们?

是的,我确实using有权访问CategoryAttribute,原因[Category("Whatever")]确实有效。我只是想知道我如何使用那些定义的常见类别。

4

2 回答 2

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

基本上,当使用反射查看类时,您可以轻松检查它属于哪个类别,而无需进行 String 比较。但是不幸的是,您不能以您尝试的方式使用它。

于 2009-03-05T14:40:16.230 回答
2

静态属性通过 CategoryAttribute.Appearance 访问。但是属性系统不允许您在属性声明中调用代码,我想这就是它不会为您编译的原因。您可能不得不满足于 [Category("Appearance")]。

于 2009-03-05T14:33:33.047 回答