特定のカスタム属性を持つアセンブリ内のすべての型を検索するメソッドを作成しようとしています。また、一致する文字列値を指定できる必要があります。注意点は、これを任意のクラスで実行して、任意の値を返すことができるようにすることです。
例:このような呼び出しを実行したい
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;
}
}
表現に精通している方のために、私は本当に次のような電話をかけられるようにしたいと思います。
TypeFinder.GetTypesWithAttributeValue<DiagnosticTestAttribute>(Assembly.Load("MyAssembly"), x=> x.TestName, "EmailTest");
式がジェネリック型を使用して、探しているプロパティを選択する場合。