什么时候应该使用在C#中的属性? [英] When should I use attribute in C#?

查看:137
本文介绍了什么时候应该使用在C#中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些使用属性的例子,例如
(作为一个地图动态厂)
<一href=\"http://msdn.microsoft.com/en-us/magazine/cc164170.aspx\">http://msdn.microsoft.com/en-us/magazine/cc164170.aspx

I saw some of the examples of utilize attribute, e.g. (as a map for dynamic factory) http://msdn.microsoft.com/en-us/magazine/cc164170.aspx

只是想知道什么是使用属性的优势在哪里?
我可以找到关于<一个参考href=\"http://msdn.microsoft.com/en-gb/z0w1kczw(VS.80).aspx\">http://msdn.microsoft.com/en-gb/z0w1kczw(VS.80).aspx
但是,我不知道的时候,我为什么要尝试使用它。

Just wondering what is the advantage of using attribute? I can find the reference on http://msdn.microsoft.com/en-gb/z0w1kczw(VS.80).aspx however, I am not sure when and why should I try to use it.

推荐答案

在.NET Framework中,属性可用于很多原因 - 像

In the .NET Framework, attributes can be used for many reasons -- like


  • 定义哪些类
    序列化

  • Defining which classes are serializable

选择哪些方法暴露
Web服务

Choosing which methods are exposed in a Web service

属性让我们的说明添加来类,属性和方法,在设计时,然后可以检查在通过反射运行。

Attributes allow us to add descriptions to classes, properties, and methods at design time that can then be examined at runtime via reflection.

考虑这个例子:

假设你有已经从旧版本的方法,它仍然是在使用以任何理由,现在你已经拿出类的新版本,这使得梦幻般的使用泛型列表和LINQ,并有一个新的方法的类类似的目的。你想开发商preFER在库的更新版本中提供的新的。你会怎么做呢?一种方法是在文档中编写。更好的方法是使用属性如下。

Say you have a class which has a method from older version which is still in use for any reason and now you have come up with a new version of the class which makes fantastic use of Generic List and LINQ and has a new method for similar purpose. You would like developers to prefer the new one provided in the later version of your library. How will you do that ? One way is to write in the documentation. A better way is to use attribute as follow.

public class AccountsManager
{
  [Obsolete("prefer GetAccountsList", true)]
  static Account[] GetAccounts( ) { }    
  static List<Account> GetAccountsList( ) { }      
}

如果一个过时程序编译时使用的方法,开发商获取此信息,并相应决定。

If an obsolete method is used when the program is compiled, the developer gets this info and decides accordingly.

AccountManager.GetAccounts()已经过时:
  preFER GetAccountsList

AccountManager.GetAccounts() is obsolete: prefer GetAccountsList

我们还可以创建并添加 自定义属性 按要求。

We may also create and add Custom Attributes as per requirements.

参考:

希望这有助于

这篇关于什么时候应该使用在C#中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆