根据C#中的用户输入解析为原始类型 [英] Parsing to primitive types, based on user input in c#

查看:102
本文介绍了根据C#中的用户输入解析为原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我执行此操作的代码使用反射和给出的字符串,而不是用户输入.最终,我希望用户能够说"float""2.0",并让计算机说,是的,这是计算机会说到的"float"或"bool""abc",这是没有听说过的布尔值.

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.

将用户输入转换为原始类型名称就足够简单了,例如将"string"转换为"System.String",将"float"转换为"System.Single",等等.(尽管您知道的功能来做到这一点,那也很棒.)

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.)

代码如下:

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);  

但是我在倒数第二行一直收到null异常.那里发生了什么事?

But I keep getting a null exception on the second to last line. What's going on there?

推荐答案

但是我在倒数第二行一直收到null异常.那里发生了什么事?

But I keep getting a null exception on the second to last line. What's going on there?

您的t.GetMethod不起作用.该方法称为Parse,而不是您编写的方法.它可能不再是模棱两可的-但这仅仅是因为它现在找不到任何方法并默默地返回null.

Your t.GetMethod doesn’t work. The method is called Parse, not what you wrote. It might no longer be ambiguous – but that’s only because it now finds no method and silently returns null.

要使呼叫明确,您需要指定期望的参数类型:

To make the call unambiguous, you need to specify the expected parameter types:

MethodInfo mi = t.GetMethod("Parse", new Type[] { typeof(string) });

这篇关于根据C#中的用户输入解析为原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆