.NET中的属性是什么,它们有什么好处,我如何创建自己的属性?


当前回答

在我目前从事的项目中,有一组不同风格的UI对象和一个编辑器来组装这些对象以创建用于主应用程序的页面,有点像DevStudio中的表单设计器。这些对象存在于它们自己的程序集中,每个对象都是从UserControl派生的类,并具有自定义属性。该属性的定义如下:

[AttributeUsage (AttributeTargets::Class)]
public ref class ControlDescriptionAttribute : Attribute
{
public:
  ControlDescriptionAttribute (String ^name, String ^description) :
    _name (name),
    _description (description)
  {
  }

  property String ^Name
  {
    String ^get () { return _name; }
  }

  property String ^Description
  {
    String ^get () { return _description; }
  }

private:
  String
    ^ _name,
    ^ _description;
};

我把它应用到这样一个课上:

[ControlDescription ("Pie Chart", "Displays a pie chart")]
public ref class PieControl sealed : UserControl
{
  // stuff
};

之前的海报也是这么说的。

要使用该属性,编辑器有一个Generic::List <Type>,其中包含控件类型。有一个列表框,用户可以从该列表框中拖放到该页上,以创建控件的实例。为了填充列表框,我获得控件的ControlDescriptionAttribute,并在列表中填写一个条目:

// done for each control type
array <Object ^>
  // get all the custom attributes
  ^attributes = controltype->GetCustomAttributes (true);

Type
  // this is the one we're interested in
  ^attributetype = ECMMainPageDisplay::ControlDescriptionAttribute::typeid;

// iterate over the custom attributes
for each (Object ^attribute in attributes)
{
  if (attributetype->IsInstanceOfType (attribute))
  {
    ECMMainPageDisplay::ControlDescriptionAttribute
      ^description = safe_cast <ECMMainPageDisplay::ControlDescriptionAttribute ^> (attribute);

    // get the name and description and create an entry in the list
    ListViewItem
      ^item = gcnew ListViewItem (description->Name);

    item->Tag = controltype->Name;
    item->SubItems->Add (description->Description);

    mcontrols->Items->Add (item);
    break;
  }
}

注:上面是c++ /CLI,但是转换成c#并不难 (是的,我知道,c++ /CLI是一个讨厌的东西,但它是我必须使用的:-()

你可以把属性放在大多数东西上,有一整套预定义的属性。上面提到的编辑器还会在描述属性以及如何编辑属性的属性上查找自定义属性。

一旦你明白了它们的全部含义,你就会想,没有它们你是怎么生活的。

其他回答

您可以使用自定义属性作为在子类中定义标记值的简单方法,而不必为每个子类反复编写相同的代码。我看到John Waters写的一个很好的简洁示例,介绍了如何在自己的代码中定义和使用自定义属性。

在http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx上有一个教程

要开始创建一个属性,打开一个c#源文件,输入attribute并点击[TAB]。它将展开为一个新属性的模板。

属性是一个类,它包含一些可以应用于代码中的对象的功能。要创建一个类,请创建一个继承自System.Attribute的类。

至于它们有什么好处……它们的用途几乎是无限的。

http://www.codeproject.com/KB/cs/dotnetattributes.aspx

很多人都回答了,但到目前为止还没有人提到这个问题……

属性与反射一起被大量使用。反射已经相当慢了。

将自定义属性标记为密封类以提高其运行时性能是非常值得的。

考虑在哪里使用place这样的属性是合适的,并通过AttributeUsage来指定属性(!),这也是一个好主意。可用属性用法的列表可能会让你大吃一惊:

组装 模块 类 结构体 枚举 构造函数 方法 财产 场 事件 接口 参数 委托 ReturnValue GenericParameter 所有

AttributeUsage属性是AttributeUsage属性签名的一部分,这也很酷。哇,循环依赖!

[AttributeUsageAttribute(AttributeTargets.Class, Inherited = true)]
public sealed class AttributeUsageAttribute : Attribute

本质上,属性是您想要附加到类型(类、方法、事件、枚举等)的数据位。

其思想是,在运行时,一些其他类型/框架/工具将在属性中查询您的类型的信息并对其进行操作。

因此,例如,Visual Studio可以查询第三方控件上的属性,以确定控件的哪些属性应该在设计时出现在“属性”窗格中。

属性还可以在面向方面编程中使用,在运行时根据装饰它们的属性注入/操作对象,并向对象添加验证、日志记录等,而不影响对象的业务逻辑。