.NET中的属性是什么,它们有什么好处,我如何创建自己的属性?
当前回答
属性是一种标记类的元数据。这通常用于WinForms中,例如在工具栏中隐藏控件,但可以在您自己的应用程序中实现,以使不同类的实例以特定的方式运行。
首先创建一个属性:
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public class SortOrderAttribute : Attribute
{
public int SortOrder { get; set; }
public SortOrderAttribute(int sortOrder)
{
this.SortOrder = sortOrder;
}
}
所有属性类必须有后缀“attribute”才有效。 完成此操作后,创建一个使用该属性的类。
[SortOrder(23)]
public class MyClass
{
public MyClass()
{
}
}
现在你可以检查一个特定类的SortOrderAttribute(如果它有的话),方法如下:
public class MyInvestigatorClass
{
public void InvestigateTheAttribute()
{
// Get the type object for the class that is using
// the attribute.
Type type = typeof(MyClass);
// Get all custom attributes for the type.
object[] attributes = type.GetCustomAttributes(
typeof(SortOrderAttribute), true);
// Now let's make sure that we got at least one attribute.
if (attributes != null && attributes.Length > 0)
{
// Get the first attribute in the list of custom attributes
// that is of the type "SortOrderAttribute". This should only
// be one since we said "AllowMultiple=false".
SortOrderAttribute attribute =
attributes[0] as SortOrderAttribute;
// Now we can get the sort order for the class "MyClass".
int sortOrder = attribute.SortOrder;
}
}
}
如果你想了解更多这方面的信息,你可以查看MSDN,那里有很好的描述。 我希望这对你有所帮助!
其他回答
属性是一个类,它包含一些可以应用于代码中的对象的功能。要创建一个类,请创建一个继承自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
属性就像应用于类、方法或程序集的元数据。
它们适用于任何数量的事情(调试器可视化,标记为过时的东西,标记为可序列化的东西,列表是无限的)。
创建您自己的自定义是很容易的。从这里开始:
http://msdn.microsoft.com/en-us/library/sw480ze8 (VS.71) . aspx
本质上,属性是您想要附加到类型(类、方法、事件、枚举等)的数据位。
其思想是,在运行时,一些其他类型/框架/工具将在属性中查询您的类型的信息并对其进行操作。
因此,例如,Visual Studio可以查询第三方控件上的属性,以确定控件的哪些属性应该在设计时出现在“属性”窗格中。
属性还可以在面向方面编程中使用,在运行时根据装饰它们的属性注入/操作对象,并向对象添加验证、日志记录等,而不影响对象的业务逻辑。
您可以使用自定义属性作为在子类中定义标记值的简单方法,而不必为每个子类反复编写相同的代码。我看到John Waters写的一个很好的简洁示例,介绍了如何在自己的代码中定义和使用自定义属性。
在http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx上有一个教程
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本