Reflection.Assembly.CreateInstance(字符串)
在.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);
}
假设classFullName是程序集中的正确类型,并且类型“T”实现公共接口,是否存在以下情况:1)不会抛出异常,并且2 ) instantiatedClass 将为 null?
感谢您的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您的假设,如果您的类型 T 始终是一个接口,那么如果所创建的实例未实现相关接口,或者该类型没有可以调用的默认构造函数,则直接转换为 T 将引发异常。
避免引发异常的更好方法是...
您可以在目标程序集上使用反射来检查所需的类型是否存在,它是否具有默认构造函数以及它是否实现您感兴趣的接口。在这种情况下,您如果您只想知道它是否具有指定的接口,那么将根本避免创建实例。
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...
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.
如果没有默认构造函数,或者 classFullName 在程序集中有效的假设不正确,或者任何阻止 CreateInstance 调用调用构造函数的因素,则会引发异常。
因此,唯一可能失败的方法是被调用的构造函数返回空值。但这不会发生,因为如果在构造过程中没有引发异常,那么构造函数调用将返回对新对象的引用,如果引发异常,您将捕获它。
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.