加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在不知道名称的情况下动态访问类中的字典

发布时间:2020-12-15 23:38:30 所属栏目:百科 来源:网络整理
导读:我有一个名为SomeClass的类.我的字典很少. public class SomeClass{ public Dictionarydouble,int[] Dict1; public Dictionarydouble,int[] Dict2; public Dictionarydouble,int[] Dict3;} 我在运行时了解字典名称.手段我需要在哪个字典中分配数据只在运行时
我有一个名为SomeClass的类.我的字典很少.

public class SomeClass
{
    public Dictionary<double,int[]> Dict1;
    public Dictionary<double,int[]> Dict2;
    public Dictionary<double,int[]> Dict3;
}

我在运行时了解字典名称.手段我需要在哪个字典中分配数据只在运行时知道.
我动态地在字符串中获取字典名称.就像是 –

String dictName = "Dict1"; //Achieved through some code mechanism in my project.

SomeClass DynValue = new SomeClass();
DynValue.[dictName/* Known at run time */].Add(3,new int[] { 5,10 });

解决方法

您应该在创建对象后初始化字典.

public class SomeClass
{
    public Dictionary<double,int[]> Dict1 = new Dictionary<double,int[]>();
    public Dictionary<double,int[]> Dict2 = new Dictionary<double,int[]> Dict3 = new Dictionary<double,int[]>();
}

要使用name动态更改对象字段,您应该使用反射:

String dictName = "Dict1"; //Achieved through some code mechanism in my project.

    SomeClass obj = new SomeClass();

    // Get dictionary interface object of 'Dict1' field using reflection
    var targetDict = obj.GetType().GetField(dictName).GetValue(obj) as IDictionary;

    // Add key and value to dictionary
    targetDict.Add(3.5d,10 });

如果您需要使用反射初始化字典,您应该使用:

String dictName = "Dict1"; //Achieved through some code mechanism in my project.

SomeClass obj = new SomeClass();

// Get field info by name
var dictField = obj.GetType().GetField(dictName);

// Get dictionary interface object from field info using reflection
var targetDict = dictField.GetValue(obj) as IDictionary;
if (targetDict == null) // If field not initialized
{
    // Initialize field using default dictionary constructor
    targetDict = dictField.FieldType.GetConstructor(new Type[0]).Invoke(new object[0]) as IDictionary;

    // Set new dictionary instance to 'Dict1' field
    dictField.SetValue(obj,targetDict);
}

targetDict.Add(3.5d,10 });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读