C#:集合元素的属性

C#: Attribute on collection element

在C#中可以将属性应用于元素,元素将被打包到集合中吗? 我有 Dictionary<string,Func<int,int,int>> 并以这种方式添加元素

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

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

所以我想向具有键 "SUM" 的元素添加额外信息,例如 "Returns summary of two numbers"。这可以用属性来完成,还是我必须在集合中包含额外的数据?

如果您查看可以将属性应用于哪些对象,您会发现您只能将其应用于程序集、Class、构造函数、委托、枚举、事件、字段、通用参数、接口、方法、模块、参数、属性、ReturnValue 或结构 (source)。您不能将属性应用于单个值,因此您必须存储额外的数据,您可以制作一个小的 class,例如:

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

然后在您的字典中使用它,例如:

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