首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我能从泛型委托中获取方法属性吗?

我能从泛型委托中获取方法属性吗?
EN

Stack Overflow用户
提问于 2012-05-15 06:48:32
回答 4查看 1.7K关注 0票数 4

我确信在论坛的某个地方已经有了答案,但到目前为止我还没有找到它。根据this example,我将匿名方法与委托结合使用,以便具有不同参数但返回类型相同的不同方法,所有方法都作为函数参数工作:

代码语言:javascript
复制
public delegate TestCaseResult Action();
...

[TestDescription("Test whether the target computer has teaming configured")]
public TestCaseResult TargetHasOneTeam()
{
  // do some logic here and return
  // TestCaseResult
}

[TestDescription("Test whether the target computer has the named team configured")]
public TestCaseResult TargetHasNamedTeam(string teamName)
{
  // do some logic here and return
  // TestCaseResult
}
...

public static void TestThat(TestCaseBase.Action action)
{
  TestCaseResult result = action.Invoke();

  // I want to get the value of the TestDescription attribute here
}
...

// usage
TestThat(() => TargetHasOneTeam());

TestThat(() => TargetHasNamedTeam("Adapter5"));

正如您从示例中看到的,我非常希望能够从TestThat()函数中获取TestDescriptionAttribute属性。我已经查看了包含我的方法的Action参数,但是还没有“找到”我的TargetHasOneTeam()方法。

EN

Stack Overflow用户

发布于 2012-05-15 07:03:27

您可以使用Attribute.GetCustomAttribute获取任何成员的属性。首先检查是否定义了该属性。例如:

代码语言:javascript
复制
public static void TestThat(TestCaseBase.Action action)
{
    TestCaseResult result = action.Invoke();
    if(System.Attribute.IsDefined(action.Method, typeof(TestDescriptionAttribute)))
    {
        var attribute = (TestDescriptionAttribute)System.Attribute.GetCustomAttribute(action.Method,
            typeof(TestDescriptionAttribute));
        Console.WriteLine(attribute.TestDescription);
    }
}
票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10592048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档