大家好我在互联网上浏览自定义属性。我掌握了这个概念但是,惊讶和混淆,看到他们通过属性类的构造函数设置属性值作为参数,该参数不从构造函数中获取任何参数作为值。请澄清核心概念。
[DeBugInfo(45, "Zara Ali", "12/8/2012", **Message = "Return type mismatch"**)]
//like the Message here.
public class DeBugInfo : System.Attribute
{
private int bugNo;
private string developer;
private string lastReview;
public string message;
public DeBugInfo(int bg, string dev, string d)
{
this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo
{
get
{
return bugNo;
}
public string Developer
{
get
{
return developer;
}
}
public string LastReview
{
get
{
return lastReview;
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
//////////////////////////
答案 0 :(得分:4)
属性语法与常规C#代码有点不同。在常规C#中,如果您手动创建该对象,那将类似于对象初始化程序:
var obj = new DeBugInfo(45, "Zara Ali", "12/8/2012") {
Message = "Return type mismatch"
};
然而,实际上,属性并不是以这种方式实际实例化,至少在它们绝对需要之前是这样。属性实际上是标记在IL中的原始元数据,包括:
您实际上可以检查所有这些信息,而无需实际创建该类型的实例。但是如果你使用Attribute.GetAttributes
等,它计算出它代表什么,并且基本上在运行时应用构造函数和映射。
完整的例子:
using System;
class DeBugInfoAttribute : Attribute
{
public string Message { get; set; }
public DeBugInfoAttribute(int i, string j, string k)
{
// to show we never get here!
throw new NotImplementedException();
}
}
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
static class Program
{
static void Main()
{
// this doesn't create the attribute, so no exception
foreach (var data in typeof(Program).GetCustomAttributesData())
{
Console.WriteLine(data.AttributeType.Name);
var parameters = data.Constructor.GetParameters();
int i = 0;
foreach (var arg in data.ConstructorArguments)
{
Console.WriteLine("{0}: {1}",
parameters[i++].Name,
arg.Value);
}
foreach (var binding in data.NamedArguments)
{
Console.WriteLine("{0}: {1}",
binding.MemberInfo.Name,
binding.TypedValue);
}
}
// but this does: BOOM!
var attribs = Attribute.GetCustomAttributes(typeof(Program));
}
}