且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候应该在 C# 中使用属性?

更新时间:2023-02-16 23:15:09

在 .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.

参考:

希望对你有帮助