[英]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"
。 可以使用屬性完成此操作,還是必須在集合中包括其他數據?
如果您查看可以應用屬性的內容,則會注意到您只能將其應用到Assembly,Class,Constructor,Delegate,Enum,Event,Field,GenericParameter,Interface,Method,Module,Parameter,Property,ReturnValue,或Struct( 源 )。 您不能將屬性應用於單個值,因此必須存儲其他數據,您可以創建一個小類,例如:
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;}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.