简体   繁体   中英

Dynamic Type instantiation C#

I'm looking to instantiate an object at runtime having its type in a string but also it's value in a string. eg:

string myType = "System.Int32";
string myValue = "3";

I'm looking to create an instance of myType and cast/assign myValue into the instance i just created.

I've looked into Activator.CreateInstance :

object objectInstance = Activator.CreateInstance(Type.GetType(myType));

But i can't get to pass my value to my instance (could be anything : int16/32/64, double, bool, custom type...).

Thank you for your help

That only works on value types...

var t = Type.GetType("System.Int32");
object x = Activator.CreateInstance(t);

if (t.IsValueType)
   x = Convert.ChangeType("2", t);

You need to get the type object and then use the Convert class:

string myType = "System.Int32";
Type type=Type.GetType(myType)

string myValue = "3";
object convertedValue = Convert.ChangeType(myValue, type);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM