根据 C# 中的用户输入解析为原始类型
我执行此操作的代码使用反射和我提供的字符串,而不是用户输入。最终,我希望用户能够说“float”“2.0”并让计算机说,是的,这是一个浮点数,或者计算机会说“bool”“abc”,这不是它听说过的布尔值。
获取用户输入并将其转换为原始类型名称非常简单,例如“string”到“System.String”,“float”到“System.Single”等(尽管如果您知道一个函数这样做,那也很棒。)
这是代码:
Console.WriteLine("1.0 => {0}", System.Single.Parse("1.0")); // this works fine.
Type t = Type.GetType("System.Single"); // for parsing floats
MethodInfo mi = t.GetMethod("System.Single.Parse"); // "ambiguous" if use "Parse"
object[] parameters = new object[] { "1.0" };
float f = (float)(mi.Invoke(null, parameters)); // get null exception here.
Console.WriteLine("Was succesfully parsed to: " + f);
但是我在倒数第二行不断收到空异常。那里发生了什么事?
My code to do this uses reflection and strings that I give it, instead of user input. Ultimately I would like the user to be able to say "float" "2.0" and have the computer say, yeah, that's a float, or "bool" "abc" to which the computer would say, that's no boolean it's heard of.
It would be simple enough to take the user input and convert it to a primitive type name, like "string" to "System.String", "float" to "System.Single", etc. (although if you know of a function to do that, that would be great too.)
Here's the code:
Console.WriteLine("1.0 => {0}", System.Single.Parse("1.0")); // this works fine.
Type t = Type.GetType("System.Single"); // for parsing floats
MethodInfo mi = t.GetMethod("System.Single.Parse"); // "ambiguous" if use "Parse"
object[] parameters = new object[] { "1.0" };
float f = (float)(mi.Invoke(null, parameters)); // get null exception here.
Console.WriteLine("Was succesfully parsed to: " + f);
But I keep getting a null exception on the second to last line. What's going on there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 t.GetMethod 不起作用。该方法称为“Parse”,而不是您编写的方法。它可能不再含糊不清 – 但这只是因为它现在找不到方法并默默返回
null
。为了使调用明确,您需要指定预期的参数类型:
Your
t.GetMethod
doesn’t work. The method is calledParse
, not what you wrote. It might no longer be ambiguous – but that’s only because it now finds no method and silently returnsnull
.To make the call unambiguous, you need to specify the expected parameter types:
要在不使用反射的情况下执行相同的操作:
为了避免无效类型的异常,您可以执行以下操作:
To do the same without using reflection:
to avoid an exception for an invalid type, you could do: