【问题标题】:How do I parse a string to a specific object type based on Type?如何根据 Type 将字符串解析为特定的对象类型?
【发布时间】:2022-06-15 21:53:55
【问题描述】:

我正在使用反射将命令行参数映射到公共属性。我最终得到的是一个蛮力方法,它接受一个字符串并返回一个特定类型的对象。如何在不为每个 C# 类型创建逻辑的情况下做到这一点?是否有设计用于执行此操作的语言或课程功能?这是我现在所拥有的。

private static object ParseValue(Type type, string argValue) {
   object parsedValue;
   if (type == typeof(int) || type == typeof(int?))
      parsedValue = int.Parse(argValue);
   else if (type == typeof(long) || type == typeof(long?))
      parsedValue = long.Parse(argValue);
   else if (type == typeof(double) || type == typeof(double?))
      parsedValue = double.Parse(argValue);
   else
      parsedValue = argValue;
   return parsedValue;
}

然后调用方法使用property.SetValue(this, parsedValue);

【问题讨论】:

标签: c# .net-core


【解决方案1】:

也许你可以使用Convert.ChangeType 方法。

在您的情况下,您可以执行以下操作,而不是调用 ParseValue 方法:

parsedValue = Convert.ChangeType(type, argValue)

其中“type”是您传递给 ParseValue 的类型。

【讨论】:

    【解决方案2】:

    如果你想玩反射,你可以使用:

    public class Program
    {
        public static void Main()
        {
            ParseValue(typeof(int), "123");
        }
        
        public static object ParseValue(Type type, string argValue)
        {
            var m = type.GetMethod("Parse", new Type[]{typeof(string)});
            var instance = Activator.CreateInstance(type);
            var result = m.Invoke(instance, new object[]{argValue});
            Console.WriteLine("The result is: " + result.ToString());
            return result;
        }
    }
    

    在调用它之前,你应该检查 Type 是否有 Parse 方法。

    查看here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 2011-03-07
      • 2019-02-15
      相关资源
      最近更新 更多