【发布时间】: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);
【问题讨论】:
-
Convert.ChangeType将涵盖常见情况。 -
使用library 为您完成。
-
这个已经在另一个帖子里回答了,看看this answer
-
这能回答你的问题吗? C# Parse string to type known at runtime