Parsing to primitive types, based on user input in

2019-05-30 01:07发布

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?

2条回答
劫难
2楼-- · 2019-05-30 02:00

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));
}
查看更多
Explosion°爆炸
3楼-- · 2019-05-30 02:03

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) });
查看更多
登录 后发表回答