如何判断父类的实例是否是从特定子项的实例创建的

dig*_*ate 5 c#

我发现通过代码示例更容易提出这个问题.

class Parent {}
class Child : Parent {}
...
...
Child firstChild = new Child();
Child secondChild = new Child();
Parent firstParent = (Parent)firstChild;
Parent secondParent = (Parent)secondChild;
Run Code Online (Sandbox Code Playgroud)

如果我不知道上述作业,如何firstParentfirstChild不访问/比较其字段或属性的情况下确定是否是从实例创建的?

Dmi*_*nko 9

那么,firstParent是不是创造了(有没有使用"new"关键字),但firstChild:

Parent firstParent = (Parent)firstChild;
Run Code Online (Sandbox Code Playgroud)

测试使用Object.ReferenceEquals(即firstParent,firstChild只是相同的实例)

if (Object.ReferenceEquals(firstParent, firstChild)) { ... }
Run Code Online (Sandbox Code Playgroud)