문제

내가 만든 사용자 지정 특성을 지 AAtribute,그리고 예를 들어 클래스라는 B 중 하나 이상 방법을 사용하여 특성이 있습니다.은 그것을 얻을 수 MethodInfo 의 방법을 보유하고 있는 특성(이 경우 BMethod1)으로(가)그 특성이없이 걷는 전체를 통해 어셈블리를 보고는 정의된 모든 방법은 자신의 속성에 대한?고 자신의 아날로그는 방법에 대한 다른 AttributeTargets(매개변수/유형/성/...)?I'don 하고의 배열에 모든 방법을 사용하는 유형의 특성,하지만 단지 방법으로 이 Attirbute-체에서 particual.나는 그것을 사용하고 싶을 넣어하는 추가에 대한 제약 방법(반품 유형,매개변수,이름,다른 속성-사용,...).

[AttributeUsage(AttributeTargets.Method)]
public class AAtribute : Attribute {

    //some fields and properties

    public AAtribute () {//perhaps with some parameters
        //some operations
        MethodInfo mi;//acces to the MethodInfo with this Attribute
                      //as an Attribute (the question)
        //some operations with the MethodInfo
    }

    //some methods

}

public class B {

    //some fields, properties and constructors

    [A]
    public void BMethod1 () {
        //some operations
    }

    //other methods

}
도움이 되었습니까?

해결책

내가 당신의 질문을 올바르게 이해했다면, 당신은 얻고 싶습니다. 속성 코드 내부, 속성이 적용되는 객체 (이 경우 방법).
나는 이것을하는 직접적인 방법이 없다고 확신합니다. 속성은 그것이 첨부 된 객체에 대한 지식이 없으며,이 연관성은 다른 방법입니다.

내가 제안 할 수있는 가장 좋은 것은 다음과 같은 해결 방법입니다.

using System;
using System.Reflection;

namespace test {

    [AttributeUsage(AttributeTargets.Method)]
    public class AAttribute : Attribute {
        public AAttribute(Type type,string method) {
            MethodInfo mi = type.GetMethod(method);
        }
    }

    public class B {
        [A(typeof(B),"BMethod1")]
        public void BMethod1() {
        }
    }
}

노트
속성의 생성자 내부에서 MethodInfo에 액세스하여 무엇을 달성하고 싶습니까? 아마도 목표를 얻는 대안적인 방법이있을 것입니다 ...

편집하다

또 다른 가능한 솔루션으로서, 당신은 당신의 속성에 정적 메소드를 제공하는 정적 메소드를 제공 할 수 있지만, 여기에는 methodinfos를 반복하는 것이 포함됩니다.

using System;
using System.Reflection;
namespace test {

    [AttributeUsage(AttributeTargets.Method)]
    public class AAttribute : Attribute {
        public static void CheckType<T>() {
            foreach (MethodInfo mi in typeof(T).GetMethods()) {
                AAttribute[] attributes = (AAttribute[])mi.GetCustomAttributes(typeof(AAttribute), false);
                if (0 != attributes.Length) {
                    // do your checks here
                }
            }
        }
    }

    public class B {
        [A]
        public void BMethod1() {
        }
        [A]
        public int BMethod2() {
            return 0;
        }
    }

    public static class Program {
        public static void Main() {
            AAttribute.CheckType<B>();
        }
    }
}

다른 팁

나는 생각한 답은 없습니다.거나 적어도지에서 합리적인 방법입니다.인스턴스의 특성은 구축 한 당신은 모습에 대한 특성을 통해 MethodInfo.인스턴스화가 있는 클래스 메소드는 특성이 인스턴스화하지 특성이 있습니다.특성이 인스턴스를 만들어 시작하면 주위를 파고들을 찾을 통해 반영합니다.

메소드에 속성이 적용되는지 확인하려면 이미 MethodInfo가 있습니다.

var type = obj.GetType();
foreach(var method in type.GetMethods())
{
    var attributes = method.GetCustomAttributes(typeof(AAtribute));
    if(attributes.Length > 0)
    {
        //this method has AAtribute applied at least once
    }
}

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top