【发布时间】:2015-09-28 08:13:53
【问题描述】:
我是属性新手,所以我试图实现的目标可能是不可能的。据我了解,属性是用于在编译时将数据绑定到特定的方法、属性、类等。
我的属性很简单,定义如下:
public class NowThatsAnAttribute : Attribute
{
public string HeresMyString { get; set; }
}
我有两个属性使用相同的自定义属性,如下所示:
public class MyClass
{
[NowThatsAnAttribute(HeresMyString = "A" )]
public string ThingyA
{
get;
set;
}
[NowThatsAnAttribute(HeresMyString = "B" )]
public string ThingyB
{
get;
set;
}
}
这一切都很好,很花哨,但我正在尝试从另一种方法访问这些属性的属性,并根据属性的值设置某些数据。
这是我现在正在做的事情:
private void MyMethod()
{
string something = "";
var props = typeof (MyClass).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(NowThatsAnAttribute)));
//this is where things get messy
//here's sudo code of what I want to do
//I KNOW THIS IS NOT VALID SYNTAX
foreach(prop in props)
{
//my first idea was this
if(prop.attribute(NowThatsAnAttribute).HeresMyString == "A")
{
something = "A";
}
else if(prop.attribute(NowThatsAnAttribute).HeresMyString == "B")
{
something = "B";
}
//my second idea was this
if(prop.Name == "ThingyA")
{
something = "A";
}
else if(prop.Name == "ThingyB")
{
something = "B";
}
}
//do stuff with something
}
问题是something 总是被设置为“B”,我知道这是由于循环属性。我只是不确定如何访问与特定属性的属性关联的值。我有一种感觉,有一种我没有看到的明显的痛苦方式。
我尝试过使用StackFrame,但在我现在所在的位置附近结束。
注意:使用 .Net 4.0。
注意2:MyMethod 是我无法编辑的界面的一部分,因此我无法传递任何参数或任何东西。
感谢任何帮助。
【问题讨论】:
-
注意,指定arrtibute时可以去掉属性名的“Attribute”部分:
[NowThatsAn(HeresMyString = "A" )]
标签: c# .net properties attributes