简体   繁体   English

Reflection.Assembly.CreateInstance(string)

[英]Reflection.Assembly.CreateInstance(string)

In .NET 4.0, if I have the following code: 在.NET 4.0中,如果我有以下代码:

....
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? 假设classFullName是程序集中的正确类型,并且类型“ T”实现了公共接口,是否有任何情况1)不会引发异常,并且2)instantiatedClass为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. 根据您的假设,并且如果类型T始终是接口,则如果所讨论的接口未由创建的实例实现,或者如果类型没有可调用的默认构造函数,则直接强制转换为T将引发异常。

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. 如果没有默认的构造函数,或者在程序集中有效的classFullName假设是不正确的,或者任何阻止CreateInstance调用的方法调用构造函数,则会引发异常。

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. 但这不会发生,因为如果在构造过程中未引发任何异常,则构造函数调用将返回对新对象的引用,并且如果引发异常,则可以捕获该异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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