简体   繁体   English

如何创建抽象类的实例?

[英]How is it possible to create an instance of an abstract class?

How is it possible for me to return an instance of the Type class with the Type.GetType(string typeName) method, when the class has previously been marked as abstract?当类以前被标记为抽象时,我怎么可能使用Type.GetType(string typeName)方法返回Type类的实例?

This is the code I used to save my MyClass class into the obj variable.这是我用来将MyClass类保存到obj变量中的代码。

Type obj = Type.GetType("ConsoleApplication.MyClass");

This is what I found when I went to the definition for the Type class.这是我在查看Type类的定义时发现的。

[NullableAttribute(0)]
[NullableContextAttribute(1)]
public abstract class Type : MemberInfo, IReflect
{

    [return: NullableAttribute(2)]
    public static Type? GetType(string typeName);

    /*
    / Other class members that, for the sake of keeping this question short, haven't been pasted 
    / into this Code sample.
    */
}

How is it possible for me to return an instance of the "Type" class with the "Type.GetType(string typeName)" method, when the class has previously been marked as abstract?当该类之前被标记为抽象类时,我怎么可能使用“Type.GetType(string typeName)”方法返回“Type”类的实例?

Because the actual object returned is a concrete sub-type of the abstract type "Type".因为返回的实际对象是抽象类型“Type”的具体子类型。 To see this run:要查看此运行:

 Type obj = Type.GetType("ConsoleApplication.MyClass");
 var typeName = obj.GetType().Name;

From the docs:从文档:

Type is an abstract base class that allows multiple implementations. Type 是一个抽象基类,允许多个实现。 The system will always provide the derived class RuntimeType.系统将始终提供派生类 RuntimeType。

Type Class 类型类

One method you can use is to call ReflectionOnlyGetType .您可以使用的一种方法是调用ReflectionOnlyGetType You must have both the name of the assembly and full class name.您必须同时拥有程序集的名称和完整的类名。 You can pass parameters to control case sensitivity and whether exceptions are thrown if no type is found.您可以传递参数来控制区分大小写以及在未找到类型时是否抛出异常。

var type = Type.ReflectionOnlyGetType("ConsoleApplication.Example, ConsoleApplication", true, true);

If you know the containing assembly, you can use the Assembly directly:如果您知道包含程序集,则可以直接使用该程序集:

var assembly = typeof(Program).Assembly; // Use any class from target assembly
var type = assembly.GetType("ConsoleApplication.MyClass");

If you are using .NET Core, it seems the ReflectionOnlyGetType is not yet implemented ( source code just throws PlatformNotSupported exception when called ), so you may have to find a way to use the second approach (which does work for .NET Core).如果您使用的是 .NET Core,则ReflectionOnlyGetType似乎尚未实现( 源代码在调用时只会抛出PlatformNotSupported异常),因此您可能需要找到一种方法来使用第二种方法(它适用于 .NET Core)。

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

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