gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:07:09 24 4
gpt4 key购买 nike

我有一个名为 SomeClass 的类。我里面几乎没有字典。

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

我在运行时知道字典名称。意味着我需要在哪个字典中分配数据只有在运行时才知道。我动态地在 string 中获取字典名称。有点像 -

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[]>();
public Dictionary<double, int[]> Dict3 = new Dictionary<double, int[]>();
}

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

    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, new int[] { 5, 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, new int[] { 5, 10 });

关于c# - 在不知道字典名称的情况下从类中动态访问字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com