简体   繁体   中英

Reflection.Assembly.CreateInstance(string)

In .NET 4.0, if I have the following code:

....
T instantiatedClass;
try
{
    instantiatedClass = (T)assembly.CreateInstance(classFullName);
}
catch (Exception ex)
{
    errMsg = string.Format("Error creating an instance of type \"{0}\".", classes.First().FullName);
    throw new ApplicationException(errMsg, ex);
}

Assuming that classFullName is a correct type in the assembly, and that the type "T" implements a public interface, is there any circumstance where 1) No exception would be thrown, and 2) instantiatedClass would be null?

Thanks for any help.

Based on your assumptions and if your type T is always an interface then a direct cast to T will throw an exception if the interface in question is not implemented by the created instance or if the type does not have a default constructor that can be called.

A better approach that avoids throwing an exception would be...

T interfaceVar = assembly.CreateInstance(classFullName) as T;
if (interfaceVar == null)
{
    // oops, does not implement interface T
}
else
{
    // yippee, it does implement interface T
}

You could use reflection on the target assembly to check if the required type exists, if it has a default constructor and if it implements the interface you are interested in. In that case you would avoid creating an instance at all, if all you want to know is if it has the specified interface.

If there is no default constructor or the assumption that classFullName is valid in the assembly is incorrect or anything prevents the CreateInstance call from calling a constructor an exception is thrown.

So the only way that this could fail for you is if the called constructor returns a null value. But this can't happen since if no exception is raised during construction, then the constructor call will return a reference to the new object, and if an exception is raised you catch it.

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