someAttribute
이라는 사용자 지정된 특성을 만들었습니다.
는 그것은 Skip
부울 부재 명명했다 다음 Main
에서메서드 내에서 특성 '멤버를 사용하는 방법
public class someAttribute : Attribute
{
public bool Skip { get; set; }
}
나는 방법 foo()
값 true
와 부재 Skip
초기화.
다음 내가 함수 속성 [someAttribute()]
을 가지고 foo()
를 호출하고 있고 회원 Skip
가 초기화 된 경우 내가 확인하려면 :
[someAttribute()]
private static int foo()
{
if(Skip)
{
return 0;
}
return 1;
}
나는 오류 "이름을받은 '건너 뛰기'에 존재하지 않는 현재 컨텍스트 "입니다.
이 속성을 사용하는 메소드 내부의 속성 멤버를 어떻게 확인할 수 있습니까?
내 전체 코드 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ConsoleApplication1
{
class ProgramTest
{
[someAttribute()]
private static int foo()
{
if(Skip)
{
return 0;
}
return 1;
}
public class someAttribute : Attribute
{
public bool Skip { get; set; }
}
public static void initAttributes()
{
var methods = Assembly.GetExecutingAssembly().GetTypes().SelectMany(t => t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
.Where(method => Attribute.IsDefined(method, typeof(someAttribute)));
foreach (MethodInfo methodInfo in methods)
{
IEnumerable<someAttribute> SomeAttributes = methodInfo.GetCustomAttributes<someAttribute>();
foreach (var attr in SomeAttributes)
{
attr.Skip = true;
}
}
}
static void Main(string[] args)
{
initAttributes();
int num = foo();
}
}
}
편집 :
나는 정적 기능 foo()
를 얻을 수있는 refelction 위해서는 BindingFlags.Static
을 추가했다.
가능한 복제 [반사 - 재산에 이름과 속성 값을 얻을] (http://stackoverflow.com/questions/6637679/reflection-get-attribute-name-and-value-on-property) – HimBromBeere
당신은'BindingFlags.Static | BindingFlags.NonPublic'은'foo' 메소드가'private static'입니다. – HimBromBeere
코드를 편집하고 추가했습니다. 감사합니다. – E235