I have 2 strings: "3.45" and "float开发者_StackOverflow中文版" so it means that I need to create a variable of float type with value = 3.45. How to do that? I guess I need to use Reflection but I cannot figure out how to assign the float variable from the string. NB Actually both strings can have any values. I need some universal code that will work with any type.
Thanks
You make take a look at the ChangeType method:
string s1 = "3.45";
string s2 = "System.Single";
Type targetType = Type.GetType(s2, true);
object result = Convert.ChangeType(s1, targetType);
And yet another one:
string s1 = "08/12/2010";
string s2 = "System.DateTime";
Type targetType = Type.GetType(s2, true);
object result = Convert.ChangeType(s1, targetType);
To handle culture specific conversions like decimal separator, datetime format there's an overload of this method that you need to use in order to pass a format provider:
string s1 = "3,45";
string s2 = "System.Single";
Type targetType = Type.GetType(s2, true);
object result = Convert.ChangeType(s1, targetType, new CultureInfo("fr-FR"));
You can use ChangeType to accomplish this
string test = "12.2";
var sam = Type.GetType("System.Single");
var val = Convert.ChangeType(test, sam);
Why do you need to create a "variable" of float/single type?
I think you want to do something with the value. Think about what you want to do with it.
If you need to pass it to another variable you can use:
object someValue = single.Parse("3.45");
If you want to call a method through reflection using a float as a dynamic parameter, you can use (credits to MSDN for most of the example):
Type magicType = Type.GetType("MagicClass");
ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
object magicClassObject = magicConstructor.Invoke(new object[]{});
// Get the ItsMagic method and invoke with a parameter value of single 3.45
MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
object magicValue = magicMethod.Invoke(magicClassObject, new object[]{ single.Parse("3.45")});
精彩评论