我的代码使用我给它的反射和字符串,而不是用户输入。最终,我希望用户能够说“float”“2.0”并让计算机说,是的,这是一个浮点数,或者计算机会说的“bool”“abc”,这不是它听说过的 bool 值。
接受用户输入并将其转换为原始类型名称就足够简单了,例如“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);
但是我在倒数第二行不断收到空异常。那里发生了什么事?
最佳答案
But I keep getting a null exception on the second to last line. What's going on there?
您的
t.GetMethod
不起作用。该方法称为 Parse
,而不是你写的。它可能不再模棱两可——但这只是因为它现在找不到任何方法并默默地返回 null
.为了使调用明确,您需要指定预期的参数类型:
MethodInfo mi = t.GetMethod("Parse", new Type[] { typeof(string) });
关于c# - 基于 c# 中的用户输入解析为原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4682910/