문제

I have following attribute definition:

[System.AttributeUsage(System.AttributeTargets.Method)]
public class ClientFunction : System.Attribute {
    public static List<???> Targets = new List<???>();
    public string Display;
    public string Tooltip;

    public ClientFunction (string display, string tooltip = null) {
        Display = display;
        Tooltip = tooltip;
        // Add target method of this specific attribute to Targets
        Targets.Add(???);
    }
}

I want to add to Targets the method the attribute is assigned to. How can I do this? Maybe with a third parameter that expects a delegate or something else?

도움이 되었습니까?

해결책 2

I think what you want to do here is this:

    [System.AttributeUsage(System.AttributeTargets.Method)]
    public class ClientFunctionAttribute : System.Attribute
    {
        private static List<MethodInfo> _targets;
        public static List<MethodInfo> Targets
        {
            get
            {
                if (_targets == null)
                {
                    _targets = Assembly.GetExecutingAssembly().GetTypes()
                  .SelectMany(t => t.GetMethods())
                  .Where(m => m.GetCustomAttributes(typeof(ClientFunctionAttribute), false).Length > 0)
                  .ToList();
                }
                return _targets;
            }
        }
        public string Display;
        public string Tooltip;

        public ClientFunctionAttribute(string display, string tooltip = null)
        {
            Display = display;
            Tooltip = tooltip;
        }
    }

And please add Attribute postfix after class name, you can still omit it in sqare brackets, like [ClientFunctionAttribute] and [ClientFunction] are the same.

다른 팁

You can't do that, attributes have no knowledge of the types/methods/etc they're assigned to.

Also, attributes constructors cannot have delegates as parameters. An attribute's parameters must be compile-time constants (e.g, strings, ints, enums). See available types: http://msdn.microsoft.com/en-us/library/aa664615%28v=vs.71%29.aspx

If you want to find all methods decorated with an attribute, you'll have to use reflection and inspect every method in every type in a given assembly, for example, and check whether those methods have the attribute defined.

Also note that, by convention, all attributes' names should be suffixed with the word "Attribute". In your case, ClientFunctionAttribute.

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