【问题标题】:How to create a dictionary in c# which can store Type as value如何在c#中创建一个可以将类型存储为值的字典
【发布时间】:2019-09-13 06:28:28
【问题描述】:

我试图将 Enum 类类型存储为 Dictionary 中的值,但我得到 'Test' 是一种类型,在给定的上下文中无效。 基本上 Test 是 Enum 类。

public enum Test
    {
        Test1 = 1,
        Test2 = 2,
    }

and Dictionary:-
private Dictionary<int, Type> _typeMapping;

【问题讨论】:

  • 也许你需要typeof(Test)
  • 你是如何尝试将枚举添加到字典中的?
  • 除了and Dictionary:-你问题sharplab.io/…中的代码没有问题
  • 个人认为不需要保存Type,可以通过Value查找Enum的Name,所以只需要一个Liststackoverflow.com/a/14971637/495455
  • @Arvind 如果您需要这样做,请显示该代码,也许我们可以帮助您以更好的方式完成它。

标签: c#


【解决方案1】:

我猜你正在做这样的事情:

_typeMapping.Add(1, Test);

什么时候应该这样做:

_typeMapping.Add(1, typeof(Test));

【讨论】:

    【解决方案2】:

    解决方案:

    class Program
    {
        private static Dictionary<int, Type> TypeMapping { get; set; }
        static void Main(string[] args)
        {
            TypeMapping = new Dictionary<int, Type>();
            Test test1 = Test.Test1;
            TypeMapping.Add((int)test1, test1.GetType());
        }
    }
    
    public enum Test
    {
        Test1 = 1,
        Test2 = 2
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-20
      • 2019-10-14
      • 2013-06-17
      • 2014-06-17
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      相关资源
      最近更新 更多