查明类型是否可实例化
在 C# 中,如何确定 Type
是否可以实例化?我试图避免 Activator.CreateInstance 异常。
我当前的方法是 type.IsClass && !type.IsInterface,但我担心这可能会在抽象类等上失败。我还考虑过检查 type.TypeInitializer == null
,但我不确定这是否万无一失。
确定 Type
是否可实例化的最简单/最有效的方法是什么?
In C#, how can I find out if a Type
can be instantiated? I am trying to avoid an Activator.CreateInstance exception.
My current method is type.IsClass && !type.IsInterface
, but I am worried this could fail on abstract classes, etc. I also considered checking type.TypeInitializer == null
, but I am not sure if that is foolproof either.
What is the simplest/most efficient way possible to find out if a Type
is instantiable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑 IsAbstract 。它将处理抽象类和静态类。您可能还想检查 IsInterface
Consider IsAbstract . It would handle abstract as well as static class. You may also want to check on IsInterface
还有许多其他陷阱。它可以有一个私有或受保护的构造函数。或者它可能没有默认构造函数,只有采用某些参数类型的构造函数。如果您必须担心这一点,那么您肯定在不应该使用 Activator.CreateInstance() 的情况下使用了它。随意构造对象只会造成严重破坏,你不知道它们可能会产生什么样的副作用。避免使用“FormatDisk”类。
一个例外是你的朋友,它告诉你你的假设是错误的。切勿故意阻止 .NET 框架发挥作用。
There are many other traps. It could have a constructor that is private or protected. Or it might not have a default constructor, only constructors that take certain argument types. If you have to worry about that then you are surely using Activator.CreateInstance() when it should not be used. Just arbitrarily constructing objects can only create havoc, you have no idea what kind of side effects they may have. Avoid the "FormatDisk" class.
An exception is your friend, it tells you that your assumptions were wrong. Never intentionally stop the .NET framework from being helpful.