【问题标题】:C#: Attribute on collection elementC#:集合元素上的属性
【发布时间】:2015-10-23 17:21:29
【问题描述】:

在 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"。这可以通过属性完成还是我必须在集合中包含其他数据?

【问题讨论】:

  • 属性适用于类型、成员、参数等,但不适用于单个值,因此您需要将其作为附加数据来执行。
  • 谢谢。请重复回答。

标签: c# reflection collections custom-attributes


【解决方案1】:

如果您查看可以将属性应用于什么,您会注意到您只能将其应用于程序集、类、构造函数、委托、枚举、事件、字段、通用参数、接口、方法、模块、参数、属性、ReturnValue 或 Struct (source)。您不能将属性应用于单个值,因此您必须存储其他数据,您可以创建一个小类,例如:

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;} 
    });

【讨论】:

    猜你喜欢
    • 2012-04-29
    • 2013-08-27
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多