我已经阅读了一些关于组件的设计时属性。在那里,我找到了一个名为 CategoryAttribute 的属性。在那个页面上它说

  

CategoryAttribute类定义以下常见类别:

然后列出一些常见的类别。其中一个是例如外观。我想,太棒了!然后我可以使用 [Category.Appearance] 代替 [Category(" Appearance")] !但显然我不能?试图写它,但Intellisense不会接受它,它不会编译。我在这里错过了什么吗?是不是这些属性不适合?如果没有,它们是为了什么?如果是,我该如何使用它们?

是的,我确实有正确的使用来访问 CategoryAttribute ,导致 [Category(“Whatever”)] 做工作。我只是想知道如何使用这些定义的常见类别。

有帮助吗?

解决方案

正如你在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);
            }

基本上,当使用反射来查看类时,您可以轻松地检查它属于哪个类别,而无需进行字符串比较。但是你不能以你想要的方式使用它。

其他提示

通过CategoryAttribute.Appearance访问静态属性。但属性系统不允许您在属性声明中调用代码,我想这就是为什么它不会为您编译。你可能不得不接受[类别(“外观”)]。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top