메소드의 속성 값 읽기
메서드 내에서 속성 값을 읽을 수 있어야합니다. 어떻게해야합니까?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}
객체 에서 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");
[MyAttribute("Hello World")]
public int MyMethod()
{
var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault();
}
사용 가능한 답변은 대부분 구식입니다.
다음은 현재 모범 사례입니다.
class MyClass
{
[MyAttribute("Hello World")]
public void MyMethod()
{
var method = typeof(MyClass).GetRuntimeMethod(nameof(MyClass.MyMethod), new Type[]{});
var attribute = method.GetCustomAttribute<MyAttribute>();
}
}
이것은 캐스팅이 필요하지 않으며 사용하기에 매우 안전합니다.
를 사용 .GetCustomAttributes<T>
하여 한 유형의 모든 속성을 가져올 수도 있습니다 .
생성시 기본 속성 값을 속성 ( Name
내 예에서는)에 저장하면 정적 속성 도우미 메서드를 사용할 수 있습니다.
using System;
using System.Linq;
public class Helper
{
public static TValue GetMethodAttributeValue<TAttribute, TValue>(Action action, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute
{
var methodInfo = action.Method;
var attr = methodInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
return attr != null ? valueSelector(attr) : default(TValue);
}
}
용법:
var name = Helper.GetMethodAttributeValue<MyAttribute, string>(MyMethod, x => x.Name);
My solution is based on that the default value is set upon the attribute construction, like this:
internal class MyAttribute : Attribute
{
public string Name { get; set; }
public MyAttribute(string name)
{
Name = name;
}
}
In case you are implementing the setup like @Mikael Engver mentioned above, and allow multiple usage. Here is what you can do to get the list of all the attribute values.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class TestCase : Attribute
{
public TestCase(string value)
{
Id = value;
}
public string Id { get; }
}
public static IEnumerable<string> AutomatedTests()
{
var assembly = typeof(Reports).GetTypeInfo().Assembly;
var methodInfos = assembly.GetTypes().SelectMany(m => m.GetMethods())
.Where(x => x.GetCustomAttributes(typeof(TestCase), false).Length > 0);
foreach (var methodInfo in methodInfos)
{
var ids = methodInfo.GetCustomAttributes<TestCase>().Select(x => x.Id);
yield return $"{string.Join(", ", ids)} - {methodInfo.Name}"; // handle cases when one test is mapped to multiple test cases.
}
}
참고URL : https://stackoverflow.com/questions/2493143/read-the-value-of-an-attribute-of-a-method
'program story' 카테고리의 다른 글
Java Generics WildCard : (0) | 2020.12.05 |
---|---|
데스크탑 경로에 대한 환경 변수는 무엇입니까? (0) | 2020.12.04 |
JavaScript 비동기 콜백에서 발생한 예외를 포착 할 수 있습니까? (0) | 2020.12.04 |
WPF에서 제출 버튼을 만드는 방법은 무엇입니까? (0) | 2020.12.04 |
전체 iPhone / iPad 앱의 배경 이미지 설정 (0) | 2020.12.04 |