2016-07-15 101 views
0

我正在做一個小型RPG(角色扮演遊戲),在對話中有影響玩家某些變量的決定。我在想,如果你知道比我更有效的方式:作爲函數參數變量?

public string Name, Nickname; 
public int Age; 

public void Decision(string Var, string Input) 
{ 
    if (Var == "Name") 
     Name = Input; 
    else if (Var == "Nickname") 
     Nickname = Input; 
    else if (Var == "Age") 
     Age = Convert.ToInt32(Input); 
} 

正如你可以看到,這是相當長僅3個變量,但也有更多...有沒有辦法做到這一點更快?事情是這樣的:

public void Decision(Variable Var, string Input) 
{ 
    Player.Var = input; 
} 

編輯:我會用兩個答案的混合:

public string Nom, Prenom; 
    public int Age; 

    public void Decision(InfoType type, string Input) 
    { 
     switch (type) 
     { 
      case InfoType.Name: 
       Nom = Input; 
       break; 
      case InfoType.Prenom: 
       Prenom = Input; 
       break; 
     } 
    } 
    public void Decision(InfoType type, int Input) 
    { 
     switch (type) 
     { 
      case InfoType.Age: 
       Age = Convert.ToInt32(Input); 
       break; 
     } 

    } 
+0

傳遞一個'object'? – melancia

+2

''int age''永遠不會'==字符串var'試試用這個代替'if(Age == Convert.ToInt32(Var){Age = Convert.ToInt32(Input);}' –

+2

爲什麼不直接把變量賦給你想要影響?假設你能夠傳遞一個「Var」的值,你就知道你想改變哪個變量。 –

回答

0

你可以做的事情有點更簡潔與switch語句,還可以使用類型的枚舉安全。例如

public enum InfoType { 
    Name, 
    Nickname, 
    Age 
} 

pubic void Decision(InfoType type, string input) 
{ 
    switch (type) 
    { 
     case InfoType.Name: 
     Name = input; 
     break; 
     case InfoType.NickName: 
     NickName = input; 
     break; 
    } 
} 

依此類推。

+0

是的,我想我會這樣做。 –

0

如何重載方法?

public void Decision(string Var, string Input) 
{ 
    if (Var == "Name") 
     Name = Input; 
    else if (Var == "Nickname") 
     Nickname = Input; 
} 

public void Decision(int Input) 
{ 
    Age = input 
} 
+0

我們強烈建議Ian利用枚舉和案例聲明來保證類型安全 –

0

您可以使用反射。缺點是你必須對複雜的類型進行額外的檢查,但對於簡單的對象,它可以像這樣工作。

public class MyObject { 
    public string Name { get; set; } 
    public string Nickname { get; set; } 
    public int Age { get; set; } 
} 

public class TestReflection { 
    public void Test() { 
     var obj = new MyObject(); 

     UpdateObject(obj, "Name", "THis is a name"); 
     UpdateObject(obj, "Age", 99); 
     UpdateObject(obj, "Nickname", "This is a nickname"); 

     Console.WriteLine("{0} {1} {2}", obj.Name, obj.Age, obj.Nickname); 
     Console.ReadLine(); 
    } 

    private void UpdateObject(MyObject obj, string varName, object varValue) { 
     //Get Properties of the object 
     var properties = obj.GetType().GetProperties(); 
     //Search for the property via the name passed over to the method. 
     var prop = properties.FirstOrDefault(_ => _.Name.Equals(varName, StringComparison.InvariantCultureIgnoreCase)); 
     //Check prop exists and set to the object. 
     if(prop != null) { 
      prop.SetValue(obj, varValue); 
     } 
    } 
}