从类型动态获取类属性值

And*_*nro 10 c# reflection custom-attributes linq-expressions

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

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

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 = string.Empty;

    public string TestName
    {
        get { return _sTestName; }
    }
    public DiagnosticTest(string sTestName)
    {
        _sTestName = sTestName;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于那些熟悉表达式的人,我真的希望能够打个电话:

TypeFinder.GetTypesWithAttributeValue<DiagnosticTestAttribute>(Assembly.Load("MyAssembly"), x=> x.TestName, "EmailTest");
Run Code Online (Sandbox Code Playgroud)

表达式使用我的泛型类型来选择我正在寻找的属性.

Seb*_*ian 13

这应该工作:

public static Type GetTypeWithAttributeValue<TAttribute>(Assembly aAssembly, Func<TAttribute, object> pred, object oValue) {
  foreach (Type type in aAssembly.GetTypes()) {
    foreach (TAttribute oTemp in type.GetCustomAttributes(typeof(TAttribute), true)) {
      if (Equals(pred(oTemp), oValue)) {
        return type;
      }
    }
  }
  return typeof(string); //otherwise return a string type
}
Run Code Online (Sandbox Code Playgroud)

甚至更好:

public static Type GetTypeWithAttributeValue<TAttribute>(Assembly aAssembly, Predicate<TAttribute> pred) {
  foreach (Type type in aAssembly.GetTypes()) {
    foreach (TAttribute oTemp in type.GetCustomAttributes(typeof(TAttribute), true)) {
      if (pred(oTemp)) {
        return type;
      }
    }
  }
  return typeof(string); //otherwise return a string type
}
Run Code Online (Sandbox Code Playgroud)

这是调用的样子:

  GetTypeWithAttributeValue<DefaultValueAttribute>(Assembly.GetCallingAssembly(), attribute => attribute.Value,
                                                    "string");
Run Code Online (Sandbox Code Playgroud)

而这一个分别是:

  GetTypeWithAttributeValue<DefaultValueAttribute>(Assembly.GetCallingAssembly(),
                                                    attribute => attribute.Value == "string");
Run Code Online (Sandbox Code Playgroud)