在运行时从字符串访问实例字典

本文关键字:实例 字典 访问 字符串 运行时 | 更新日期: 2023-09-27 18:16:38

[Serializable]
public class DOCharStats
{
    public int Stamina { get; set; }
    public int maxStamina { get; set; }
}
[Serializable]
public class DOMapStats
{
    public int xlocation { get; set; }
    public int ylocation { get; set; }
}
//Name of char and stats
public static Dictionary<string, DOCharStats> dCharStats = new Dictionary<string, DOCharStats>();
public static Dictionary<string, DOMapStats> dMapStats = new Dictionary<string, DOMapStats>();
//Name of container and dict.
public static Dictionary<string, object> dContainer = new Dictionary<string, object>();
static void Main(string[] args)
{
    DOCharStats newStats = new DOCharStats();
    dCharStats.Add("MC", newStats);
    Console.WriteLine(dCharStats["MC"].Stamina);
    Console.WriteLine(dCharStats["MC"].maxStamina);

    newStats.Stamina = 5;
    newStats.maxStamina = 10;
    Console.WriteLine(dCharStats["MC"].Stamina);
    Console.WriteLine(dCharStats["MC"].maxStamina);
    DOMapStats mapstats = new DOMapStats();
    mapstats.xlocation = 20;
    mapstats.ylocation = 40;
    dMapStats.Add("MC", mapstats);

    //How to access dCharStats(dictionary variant) from a string?
    dContainer.Add("_dCharStats",dCharStats);
    dContainer.Add("_dMapStats", dMapStats);
}

dCharStatsdMapStats将在程序运行时被其他方法修改。

我想访问&根据字符串修改dCharStatsdMapStats。我试过通过dContainer这样做,但我无法以通用的方式将dCharStats(object)转换为dCharStats(Dictionary<String,DOCharStats>)

是否有一种方法可以在运行时从字符串访问实例字典(dCharStats) ?

在运行时从字符串访问实例字典

        dContainer.Add(_dCharStats, dCharStats);
        dContainer.Add("_dMapStats", dMapStats);
        object secondObj = (object)dCharStats;
        dynamic someObj = dContainer[_dCharStats];
        foreach (dynamic blah in someObj)
        {
            dynamic internalObj = blah.Value;
            int somevalue = internalObj.GetType().GetProperty("Stamina").GetValue(internalObj, null);
            internalObj.GetType().GetProperty("Stamina").SetValue(internalObj, 8080, null);
        }
        Console.WriteLine("After:"+dCharStats["MC"].Stamina);
        Console.WriteLine("After:" + dCharStats["MC"].maxStamina);

一两个小时后发布这个,看起来使用动态变量解决了我的问题。