【问题标题】:Converting strings (Loaded from Json file) to Formattable string将字符串(从 Json 文件加载)转换为可格式化字符串
【发布时间】:2023-01-20 08:12:10
【问题描述】:

我有一个 Json 文件,其中的字符串用内部变量编写,格式与插值字符串相同,但是在加载字符串时,我无法将它们转换为可格式化字符串,所以我想知道是否可以转换我得到的字符串可格式化的字符串,还是我需要编写自己的类来用字符串中的值替换变量名称?

在声明具有字符串的变量之前,我曾尝试放置一个 $ 符号,但我最终遇到了一些错误。 我还尝试通过这样做直接将字符串转换为 Formattable string/IFormattable:

(FormattableString) loaded_text;

这就是所有想到的,但没有一个奏效。

【问题讨论】:

  • 您能否添加更多细节,例如你的 json 和你用来反序列化它的代码,以及你到底是如何尝试使用这些字符串的?

标签: c# json string unity3d string-interpolation


【解决方案1】:

好吧,通过使用 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;
    }

我希望有人觉得这很有用,如果您认为代码中可以改进某些地方,请慷慨地与我分享。

【讨论】:

    猜你喜欢
    • 2019-04-01
    • 2020-09-09
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多