将字符串中的值解析为未知变量类型

Log*_*gan 5 c# parsing

对于我正在开发的游戏(在C#中),我们需要能够保存和加载选项文件,为了便于使用,我们决定以纯文本形式进行.我有一个问题,但是当我尝试将文本加载到他们的变量中时,因为我并不总是知道需要加载什么类型的变量.

下面的代码行有效,除了我还没有找到类似的功能

f.GetType().Parse()
Run Code Online (Sandbox Code Playgroud)

这是实际的代码

OptionsClass current = new OptionsClass();  
    using(StreamReader reader = new StreamReader(path)){
        string line;
        while((line = reader.ReadLine()) != null){
        foreach(FieldInfo f in typeof(OptionsClass).GetFields()){
            f.SetValue(current, f.GetType().Parse(line.Split(new char[] {'='})[1]));

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有什么不清楚,或者需要更多信息,请告诉我.问候,-Logan

com*_*ech 6

我建议您使用内置的XML或JSON序列,而不是自己尝试这样做.

但是,如果您要自己实现,那么我建议您对字段类型执行切换,并根据字段的数据类型转换值.例如:

        string sValue = line.Split(new char[] {'='})[1]);
        object oValue;
        switch (f.FieldType.Name.ToLower())
        {
            case "system.string":
               oValue = sValue;
               break;

            case "system.int32":
                oValue = Convert.ToInt32(sValue);
                break;
         etc...

      f.SetValue(current, oValue);
Run Code Online (Sandbox Code Playgroud)

还有一个注意事项:如果你要使用自建路由,那么你可能希望在数据转换中更加健壮(即检查字符串是否为空并且在转换为数字时是数字等) .