我以前在日常工作中没有使用过属性,但我已经阅读过它们。 另外我做了一些测试,以备份我在这里要说的内容。如果我在任何地方都错了 - 随时告诉我这个:)
从我所知道的,属性并不像普通类一样。当你创建一个应用对象时,它们不会被实例化,而不是一个静态实例,而不是每个对象的实例。 他们也没有访问他们应用到的类。
相反,它们的作用类似于类的属性(属性?:P)。不像.NET类属性,更像是在“玻璃的一种属性是透明度”类属性中。您可以通过反射来检查哪些属性应用于某个类,然后对其进行相应处理。它们实质上是连接到类定义的元数据,而不是该类型的对象。
你可以尝试获取一个类,方法,属性等等的属性列表。当你得到这些属性的列表 - 这是他们将被实例化的地方。然后您可以对这些属性中的数据采取行动。
E.g. Linq表中,属性具有定义它们引用的表/列的属性。但是这些类不使用这些属性。相反,DataContext会在将linq表达式树转换为SQL代码时检查这些对象的属性。
现在对于一些真实的例子..我已经在LinqPad中跑过这些,所以不要担心奇怪的Dump()方法。我已经为Console.WriteLine取代它使代码更容易理解不知道是谁做这件事:)
void Main()
{
Console.WriteLine("before class constructor");
var test = new TestClass();
Console.WriteLine("after class constructor");
var attrs = Attribute.GetCustomAttributes(test.GetType()).Dump();
foreach(var attr in attrs)
if (attr is TestClassAttribute)
Console.WriteLine(attr.ToString());
}
public class TestClassAttribute : Attribute
{
public TestClassAttribute()
{
DefaultDescription = "hello";
Console.WriteLine("I am here. I'm the attribute constructor!");
}
public String CustomDescription {get;set;}
public String DefaultDescription{get;set;}
public override String ToString()
{
return String.Format("Custom: {0}; Default: {1}", CustomDescription, DefaultDescription);
}
}
[Serializable]
[TestClass(CustomDescription="custm")]
public class TestClass
{
public int Foo {get;set;}
}
这种方法的控制台结果是人们:
before class constructor
after class constructor
I am here. I'm the attribute constructor!
Custom: custm; Default: hello
而Attribute.GetCustomAttributes(test.GetType())
返回此阵: (该表显示所有可用的列所有条目。所以,不,Serializable属性不具备这些属性:))
得到任何MOR问题?随意问!
UPD: 我见过你问一个问题:为什么使用它们?作为一个例子,我会告诉你关于XML-RPC.NET库。 您将创建您的XML-RPC服务类,并使用代表xml-rpc方法的方法。现在最主要的是:在XmlRpc中,方法名可以有一些特殊字符,如点。所以,你可以有一个flexlabs.ProcessTask()xml rpc方法。同时仍然使用公用名称,因为它必须是
[XmlRpcMethod("flexlabs.ProcessTask")]
public int ProcessTask_MyCustomName_BecauseILikeIt();
这让我的名字在我喜欢的方式方法,:
你会这样定义这个类。
+1大家有帮助的答案。现在我清楚地明白,属性本身不会有任何行为,也不会改变它们所应用的类的行为。它们只是额外的元数据固定到一个类。因此,我认为“行为”实际上不是属性类的代码,而是其他代码,如Serialize方法,解释元数据并使用它来有条件地执行操作(例如查看Serializable属性的Serialize方法)。 – AaronLS 2010-04-20 18:26:21
查看属性构造函数何时运行的很好的示例:http://stackoverflow.com/a/1168590/84206 – AaronLS 2014-06-25 19:31:39