简体   繁体   中英

C#: Attribute on collection element

In C# can attribute be applied to element, which will be packed in collection? I have Dictionary<string,Func<int,int,int>> and add elements in that way

Dictionary<string,Func<int,int,int>> dict = new Dictionary<string,Func<int,int,int>>();

dict.Add("SUM", (a,b) => {return a+b;});

So I want add additional information to element with key "SUM" such as "Returns summary of two numbers" . Can this be done with attributes or I must include additional data in collection?

If you look at what you can apply an attribute to, you'll notice you can only apply it to Assembly, Class, Constructor, Delegate, Enum, Event, Field, GenericParameter, Interface, Method, Module, Parameter, Property, ReturnValue, or Struct ( source ). You can't apply attributes to individual values so you will have to store additional data, you could make a small class, something like:

public class Operation
{
    public string Description {get;set;}
    public Func<int, int, int> Func {get;set;}
}

And then use it in your dictionary like:

dict.Add("SUM", new Operation() { 
    Description = "Adds numbers", 
    Func = (a,b) => {return a+b;} 
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM