找出声明为超类的实例的子类类型

时间:2022-07-14 17:01:21

Assuming I have the superclass A, and the subclasses A1 and A2 which inherit from A, how could I get the subclass type of the variables in the code below?

假设我有超类A,以及继承自A的子类A1和A2,我怎样才能在下面的代码中获得变量的子类类型?

A _a1 = new A1();
A _a2 = new A2();
// Need type of A1 and A2 given the variables _a1 and _a2.

Also, if I had another subclass A2_1 which is a sublcass of A2, how do I get the lowest subclass type given code below?

另外,如果我有另一个子类A2_1,它是A2的子级,我如何获得下面给出代码的最低子类类型?

A _a2_1 = new A2_1();

EDIT: Thanks for answers. What a boo boo. Over thinking the problem and didn't even try GetType(). =/

编辑:谢谢你的回答。真是个嘘声。过度思考问题,甚至没有尝试GetType()。 = /

4 个解决方案

#1


Console.WriteLine(_a1.GetType());

GetType can return the run-time type of the variable irrespective of declaration type.

无论声明类型如何,GetType都可以返回变量的运行时类型。

#2


You could use the GetType() method:

您可以使用GetType()方法:

Type type = _a1.GetType();
Type subtype = _a2_1.GetType();

#3


For the first - just use _a1.GetType() and _a2.GetType(). On the 2nd - what do you mean by "lowest subclass type"; or: what answer do you expect... (which might help us understand what you mean...)

对于第一个 - 只需使用_a1.GetType()和_a2.GetType()。在第二个 - “最低子类型”是什么意思;或者:你期望得到什么答案......(这可能有助于我们理解你的意思......)

#4


GetType() on any object always gives you the real object type, never the type of a superclass. If you are creating instances of subclasses using "new subclass()", then "subclass" is the Type of the object.

任何对象上的GetType()总是为您提供真实的对象类型,而不是超类的类型。如果使用“new subclass()”创建子类的实例,则“subclass”是对象的Type。

Calling GetType() is all you need for your situations.

只需调用GetType()就可以满足您的需求。

#1


Console.WriteLine(_a1.GetType());

GetType can return the run-time type of the variable irrespective of declaration type.

无论声明类型如何,GetType都可以返回变量的运行时类型。

#2


You could use the GetType() method:

您可以使用GetType()方法:

Type type = _a1.GetType();
Type subtype = _a2_1.GetType();

#3


For the first - just use _a1.GetType() and _a2.GetType(). On the 2nd - what do you mean by "lowest subclass type"; or: what answer do you expect... (which might help us understand what you mean...)

对于第一个 - 只需使用_a1.GetType()和_a2.GetType()。在第二个 - “最低子类型”是什么意思;或者:你期望得到什么答案......(这可能有助于我们理解你的意思......)

#4


GetType() on any object always gives you the real object type, never the type of a superclass. If you are creating instances of subclasses using "new subclass()", then "subclass" is the Type of the object.

任何对象上的GetType()总是为您提供真实的对象类型,而不是超类的类型。如果使用“new subclass()”创建子类的实例,则“subclass”是对象的Type。

Calling GetType() is all you need for your situations.

只需调用GetType()就可以满足您的需求。