小编And*_*nro的帖子

从类型动态获取类属性值

我正在尝试编写一个方法,在具有特定自定义属性的程序集中查找所有类型.我还需要能够提供匹配的字符串值.需要注意的是,我希望能够在任何类上运行它并返回任何值.

例如:我想执行这样的调用

Type tTest = TypeFinder.GetTypesWithAttributeValue(Assembly.Load("MyAssembly"), typeof(DiagnosticTestAttribute), "TestName", "EmailTest");
Run Code Online (Sandbox Code Playgroud)

到目前为止我的方法看起来像这样:

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
}
Run Code Online (Sandbox Code Playgroud)

我的属性看起来像这样:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class DiagnosticTestAttribute : Attribute
{
    private string _sTestName …
Run Code Online (Sandbox Code Playgroud)

c# reflection custom-attributes linq-expressions

10
推荐指数
1
解决办法
1万
查看次数