好吧,通过使用 System.Text.RegularExpressions(简称 Regex),并在这样的类中存储我需要的所有属性:
public string player_first { get{return player.firstName;} private set {} }
public string player_last { get{return player.lastName;} private set{}}
public string player_full {get {return player.firstName + " " + player.lastName;} private set {}}
public string player_age { get{return player.age.ToString(); } private set{}}
public string player_height {get {return player.height.ToString(); } private set{}}
//conditions
public bool player_isOld { get {return player.age >= 65;} private set{}}
public bool player_isYoung {get {return player.age<65;} private set{}}
我使用 Regex 手动搜索大括号之间的每个字符串和我制作的这个函数:
private string fixMatch(Match match)
{
return match.ToString().Replace("{", "").Replace("}", "");
}
然后使用以下函数在类中搜索属性:
public T GetProperty<T>(string name)
{
return (T) typeof(PropertiesManager).GetProperty(name).GetValue(this, null);
}
现在只需使用这几行代码将所有变量名替换为变量值即可:
public string fromatString(string text)
{
string new_text = text;
var matches = Regex.Matches(text, "{(.*?)}");
foreach(Match match in matches)
{
Debug.Log(match);
string temp = GetProperty<string>(fixMatch(match));
new_text = new_text.Replace(match.ToString(), temp);
}
return new_text;
}
我希望有人觉得这很有用,如果您认为代码中可以改进某些地方,请慷慨地与我分享。