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

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

问题描述

我看到了一些利用属性的例子,例如(作为动态工厂的地图)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

只是想知道使用属性有什么好处?我可以在 http://msdn.microsoft.com/上找到参考资料zh-CN/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

选择公开的方法网络服务

Choosing which methods are exposed in a Web service

Attributes 允许我们在设计时将 descriptions 添加到类、属性和方法中,然后可以在运行时通过反射进行检查.

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

考虑这个例子:

假设你有一个类,它有一个旧版本的方法,由于任何原因仍在使用,现在你想出了一个新版本的类,它很好地利用了 Generic List 和 LINQ,并有了一个新方法出于类似目的.您希望开发人员更喜欢在您的库的更高版本中提供的新版本.你会怎么做?一种方法是写在文档中.更好的方法是使用属性如下.

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( ) { }      
}

如果在编译程序时使用了 obsolete 方法,开发者会得到这个信息并做出相应的决定.

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

AccountManager.GetAccounts() 已过时:更喜欢 GetAccountsList

AccountManager.GetAccounts() is obsolete: prefer GetAccountsList

我们还可以创建和添加 自定义属性根据要求.

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

参考:

希望对你有帮助

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

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