5 分钟了解 C# 属性






4.85/5 (126投票s)
在本文中,我们将尝试了解 C# 属性。
什么是属性,我们为什么需要它?
“属性只不过是一段信息”。
此信息可以附加到您的方法、类、命名空间、程序集等。属性是您代码的一部分,这使开发人员的生活更轻松,因为当他调用方法或访问类时,可以直接在代码中看到该信息,并据此采取行动。
例如,下面是一个简单的类,其中“Method1”被“Obsolete”属性修饰。 属性使用“[]”符号定义。 因此,当开发人员开始在此类中编写代码时,他们会收到警告,“Method1”已过时,现在应该在“NewMethod1”中编写代码。
public class Class1
{
[Obsolete]
public void Method1()
{
}
public void NewMethod1()
{
}
}
同样,如果有人尝试创建“Class1”的对象,他会在工具提示中收到警报,如下面的代码片段所示,“Method1”已过时,他应该使用“NewMethod1”。
简而言之,属性只不过是一小段信息,它以声明方式嵌入在代码本身中,开发人员可以预先看到。
如果您想向开发人员显示一些消息,您可以在“Obsolete”属性中传递消息,如下面的代码片段所示。
[Obsolete("Please use NewMethod1")]
public void Method1()
{
}
如果您想更加严格,并且不希望开发人员使用该方法,您可以将“true”传递给“Obsolete”属性,如下面的代码所示。
[Obsolete("Please use NewMethod1",true)]
public void Method1()
{
}
现在,如果开发人员尝试调用“Method1”,他们将收到错误,而不仅仅是一个简单的警告。
我们如何创建自定义属性?
我们上面讨论的“Obsolete”属性是一个现成的属性。要创建自定义属性,您需要从属性类继承。下面是一个简单的“HelpAttribute”,它具有“HelpText”属性。
class HelpAttribute : Attribute
{
public string HelpText { get; set; }
}
“HelpAttribute”应用于下面的代码所示的“Customer”。现在,看到这个类的开发人员,可以直接在他们眼前看到信息。
[Help(HelpText="This is a class")]
class Customer
{
private string _CustomerCode;
[Help(HelpText = "This is a property")]
public string CustomerCode
{
get { return _CustomerCode; }
set { _CustomerCode = value; }
}
[Help(HelpText = "This is a method")]
public void Add()
{
}
}
是否可以限制自定义属性仅用于方法?
通过使用“AttributeUsage”和“AttributeTargets”,您可以将属性限制到特定部分,如类、方法、属性等。 下面是一个简单的自定义属性,现在仅限于方法。
[AttributeUsage(AttributeTargets.Method)]
class HelpAttribute : Attribute
{
public string HelpText { get; set; }
}
如果您尝试将上述属性应用于类或属性,您将收到编译时错误,如下所示。
您还可以将属性限制为类、构造函数、程序集等。 以下是您可以限制属性的可能性的列表。
除了信息之外,我们还能做什么?
到目前为止,我们讨论过的一个用途是供开发人员在编码时查看信息并相应地做出决定。 另一个用途是,您可以使用反射以编程方式读取信息并对其进行操作。
例如,下面是一个自定义属性,它描述了类的属性的字符长度。
[AttributeUsage(AttributeTargets.Property)]
class Check : Attribute
{
public int MaxLength { get; set; }
}
下面是一个客户类,该属性被修饰,提供信息“CustomerCode”属性的最大长度不能超过 10 个字符。
class Customer
{
private string _CustomerCode;
[Check(MaxLength = 10)]
public string CustomerCode
{
get { return _CustomerCode; }
set { _CustomerCode = value; }
}
}
下面是动态循环遍历每个属性的属性并进行长度验证检查的代码。
因此,第一步是创建客户类的对象。
// Create the object of Customer class
// and load it with some data
Customer obj = new Customer();
obj.CustomerCode = "12345678901";
第二步是获取对象的“Type”。 因为一旦我们获取了对象的类型,我们就可以浏览对象的属性、方法等。
// Get the type of the object
Type objtype = obj.GetType();
使用“Type”对象并循环遍历所有属性以及这些属性的属性。
// Loop through all properties
foreach (PropertyInfo p in objtype.GetProperties())
{
// for every property loop through all attributes
foreach (Attribute a in p.GetCustomAttributes(false))
{
}
}
一旦您掌握了该属性,您就可以进行长度检查并相应地引发异常。
// Loop through all properties
foreach (PropertyInfo p in objtype.GetProperties())
{
// for every property loop through all attributes
foreach (Attribute a in p.GetCustomAttributes(false))
{
Check c = (Check)a;
if (p.Name == "CustomerCode")
{
// Do the length check and and raise exception accordingly
if (obj.CustomerCode.Length > c.MaxLength)
{
throw new Exception(" Max length issues ");
}
}
}
}
属性会被继承吗?
是的,它们在子类中被继承。
如果我们想阻止某些属性被继承怎么办?
我们在“AttributeUsage”中有一个“Inherited”属性,如果我们将它设置为 false,这些属性将不会在子类中被继承。
[AttributeUsage(AttributeTargets.Property,Inherited=false)]
class Check : Attribute
{
publicintMaxLength { get; set; }
}
如果我希望属性在程序中只使用一次怎么办?
如果您将“AllowMultiple”指定为 true,则可以在同一程序中多次使用它。
[AttributeUsage(AttributeTargets.Property,AllowMultiple=false)]
class Check : Attribute
{
public int MaxLength { get; set; }
}
观看下面的 Facebook 视频,其中解释并实际演示了 C# 属性。
进一步阅读,请观看下面的面试准备视频和分步视频系列。