Parsing to primitive types, based on user input in c#

安稳与你 提交于 2019-12-08 03:39:50

问题


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?


回答1:


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

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



回答2:


To do the same without using reflection:

Console.WriteLine(Convert.ChangeType("42", Type.GetType("System.Int32")));
Console.WriteLine(Convert.ChangeType("42.123", Type.GetType("System.Single")));

to avoid an exception for an invalid type, you could do:

string typeStr = "System.Single";

Type type = Type.GetType(typeStr);

if (type != null)
{
    Console.WriteLine(Convert.ChangeType("42", type));
}


来源:https://stackoverflow.com/questions/4682910/parsing-to-primitive-types-based-on-user-input-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!