Convert an object to a type based on the string value passed in C#
I have a requirement where the object type [name of the object] is passed as a string variable. Now based on the object name passed, I need to create that object type. Please note the string value contains the exact object type name. I have written a code snippet but it is throwing an exception.
e.g -
string objectName = "EntityTest.Entity.OrderEntity";//Entity type name
object obj = new object();
object newobj = new object();
newobj = Convert.ChangeType(obj, Type.GetType(objectName));
I do this I get error -- > Object must implement IConvertible.
My entity OrderEntity
has already implemented the IConvertible
inte开发者_运维百科rface.
Any help/suggestion is greatly appreciated. Is there any other way I can create the object to fulfill my requirement.
You're currently trying to convert an existing object, rather than creating one of the right type. Assuming your Type.GetType
call is working, you can just use:
Type type = Type.GetType(objectName);
object x = Activator.CreateInstance(type);
A few points to note:
Type.GetType(string)
requires an assembly-qualified name unless the type is either in the currently-executing assembly ormscorlib
Activator.CreateInstance(Type)
will call the parameterless constructor (which has to be accessible); if you need to pass arguments to the constructor, there are other overloads available.
Your problem is that you're creating an instance of object
and then trying to cast that to a more specific type (which it can't be).
You need a way to call the default constructor of the type that you're trying to create. Take a look at Activator.CreateInstance()
:
var type = Type.GetType(typeName);
var instance = Activator.CreateInstance(type);
If the type has no default constructor, the above example will fail. In that case, your best bet is probably to use this overload (that takes an array of objects to use as constructor parameters and then tries to find the best match)
精彩评论