Question

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?

Was it helpful?

Solution 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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top