【问题标题】:How get the value of the attribute provide to a method in C# [duplicate]如何获取属性的值提供给 C# 中的方法 [重复]
【发布时间】:2016-08-03 13:40:20
【问题描述】:
public class A
{
    [Description("This method does something")]
    public void TestMethod()
     {
       //Do Something
     }
}

我的问题是如何使用反射获取描述属性的字符串值。

【问题讨论】:

标签: c#


【解决方案1】:
var description = ((DescriptionAttribute)typeof (A).GetMethod("TestMethod")
    .GetCustomAttribute(typeof (DescriptionAttribute))).Description;

【讨论】:

  • public void GetDescription() { MethodInfo[] methods = typeof(A).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); Dictionary methodInformations = new Dictionary(); foreach(var 方法中的方法) { object attrs = method.GetCustomAttribute(typeof(DescriptionAttribute)); DescriptionAttribute decr = attrs as DescriptionAttribute; methodInformations.Add(method.Name, decr.Description); } }
  • 上述方法还帮助我过滤了基类方法,因为 A 类是派生类
【解决方案2】:

你可以这样试试:

MethodBase m = typeof(A).GetMethod("TestMethod");;
Description d = (Description)m.GetCustomAttributes(typeof(Description), true)[0] ;
string str= d.Value; 

【讨论】:

    猜你喜欢
    • 2011-07-25
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多