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

C# 如何判断父类的实例是否是从特定子类的实例创建的,c#,C#,我发现通过一个代码示例更容易问这个问题 class Parent {} class Child : Parent {} ... ... Child firstChild = new Child(); Child secondChild = new Child(); Parent firstParent = (Parent)firstChild; Parent secondParent = (Parent)secondChild; 如果我不了解上述分配,我如何确定是否从实例firstChild创

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

class Parent {}
class Child : Parent {}
...
...
Child firstChild = new Child();
Child secondChild = new Child();
Parent firstParent = (Parent)firstChild;
Parent secondParent = (Parent)secondChild;

如果我不了解上述分配,我如何确定是否从实例
firstChild
创建了
firstParent
,而不访问/比较它们的字段或属性

好的,
firstParent
不是创建的(没有使用“new”关键字),而是从
firstChild
强制转换的:

Parent firstParent = (Parent)firstChild;
要测试,请使用
对象。引用equals
(即
firstParent
firstChild
是同一个实例)


简单的相等运算符应该可以工作。如果
等于
方法未被重写

Child firstChild = new Child();
Child secondChild = new Child();
Parent firstParent = (Parent) firstChild;
Parent secondParent = (Parent) secondChild;

Console.WriteLine(firstParent == firstChild); // true
Console.WriteLine(firstParent == secondChild); // false
因为对象的默认相等方法是通过引用进行检查

Equals的默认实现支持引用类型的引用相等,以及值类型的位相等。引用相等是指被比较的对象引用引用同一对象。按位相等意味着被比较的对象具有相同的二进制表示

Child firstChild = new Child();
Child secondChild = new Child();
Parent firstParent = (Parent) firstChild;
Parent secondParent = (Parent) secondChild;

Console.WriteLine(firstParent == firstChild); // true
Console.WriteLine(firstParent == secondChild); // false