动态获取类属性值我试图编写一个方法,该方法可以查找具有特定自定义属性的程序集中的所有类型。我还需要能够提供匹配的字符串值。需要注意的是,我希望能够在任何课程上运行此操作并返回任何值。从类型
例如: 我想执行像调用此
Type tTest = TypeFinder.GetTypesWithAttributeValue(Assembly.Load("MyAssembly"), typeof(DiagnosticTestAttribute), "TestName", "EmailTest");
我的方法,到目前为止是这样的:
public static Type GetTypesWithAttributeValue(Assembly aAssembly, Type tAttribute, string sPropertyName, object oValue)
{
object oReturn = null;
foreach (Type type in aAssembly.GetTypes())
{
foreach (object oTemp in type.GetCustomAttributes(tAttribute, true))
{
//if the attribute we are looking for matches
//the value we are looking for, return the current type.
}
}
return typeof(string); //otherwise return a string type
}
我的属性是这样的:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class DiagnosticTestAttribute : Attribute
{
private string _sTestName = string.Empty;
public string TestName
{
get { return _sTestName; }
}
public DiagnosticTest(string sTestName)
{
_sTestName = sTestName;
}
}
对于那些熟悉表情的人,我真的很想打个电话给李ke:
TypeFinder.GetTypesWithAttributeValue<DiagnosticTestAttribute>(Assembly.Load("MyAssembly"), x=> x.TestName, "EmailTest");
其中表达式使用我的泛型类型来选择我正在寻找的属性。
这工作完美无瑕。我不得不改变装配,因为我从另一个装置调用装配,但效果很好。谢谢一堆。 –
如果我可以给你更多的信誉,我会;-) – Seabizkit