我经常想知道两个变量是否指向同一个类的实例。听起来很明显,但是能做到吗?
例如。想象一下你有以下带有名为“IsSameInstanceAs”的运算符的代码。在使用.Net、C#时,是否有任何方法可以根据if语句内部的注释满足“IsSameInstanceAs”运算符的逻辑:
public class MyClass
{
public String MyString;
public static void TestForSameInstance()
{
MyClass myInstanceA = new MyClass();
MyClass myInstanceB = myInstanceA;
MyClass myInstanceC = new MyClass();
myInstanceA.MyString = "A String";
myInstanceC.MyString = myInstanceA.MyString;
if (myInstanceA IsSameInstanceAs myInstanceB)
{
// These are the same instance so they will match and this if is true
}
if (myInstanceA IsSameInstanceAs myInstanceC)
{
// These are not the same instance so they will not match and this if is false
}
}
}
我相信这是无法实现的,但如果有人知道更好的方法,请帮忙解答。请注意,我不想比较对象实例,我想知道它们是否是同一个实例。
约翰·汤普森