2015-10-08 71 views
-1
[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)?

+0

你是什麼意思我無法以通用方式強制轉換爲字典?不能你只是'(Dictionary )dContainer [「_ dCharStats」]'? –

+0

這裏是關於如何創建和訪問字典的教程<> http://www.csharp-station.com/Tutorial/CSharp/Lesson20 – MethodMan

+0

這裏的問題是指定DOCharStats作爲類型。我有幾種不同的數據對象類。這將需要爲每個新的DO類編寫代碼。 – MrSean

回答

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

發表這個之後的一兩個小時,它看起來像使用動態變量解決了我的問題。