读取方法属性的值

我需要能够从我的方法中读取属性的值,该怎么办?


[MyAttribute("Hello World")]

public void MyMethod()

{

    // Need to read the MyAttribute attribute and get its value

}


三国纷争
浏览 472回答 2
2回答

阿波罗的战车

您需要GetCustomAttributes在MethodBase对象上调用该函数。获取MethodBase对象的最简单方法是调用MethodBase.GetCurrentMethod。(请注意,您应该添加[MethodImpl(MethodImplOptions.NoInlining)])例如:MethodBase method = MethodBase.GetCurrentMethod();MyAttribute attr = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), true)[0] ;string value = attr.Value;    //Assumes that MyAttribute has a property called Value您也可以MethodBase手动获取,例如:(这样会更快)MethodBase method = typeof(MyClass).GetMethod("MyMethod");

Smart猫小萌

可用的答案大多已过时。这是当前的最佳做法:class MyClass{&nbsp; [MyAttribute("Hello World")]&nbsp; public void MyMethod()&nbsp; {&nbsp; &nbsp; var method = typeof(MyClass).GetRuntimeMethod(nameof(MyClass.MyMethod), new Type[]{});&nbsp; &nbsp; var attribute = method.GetCustomAttribute<MyAttribute>();&nbsp; }}这不需要铸造,使用起来非常安全。您还可以.GetCustomAttributes<T>用来获取一种类型的所有属性。
打开App,查看更多内容
随时随地看视频慕课网APP