微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 比较两个托管引用

如果它们相等,是否可以比较两个托管引用(类型为ref T)?我不是指对象的引用,而是对变量的引用.例:

public static bool Compare(ref int a,ref int b)
{
    return ref a == ref b; //something like that,not possible this way in C#
}

int x,y;
Compare(ref x,ref x); //true
Compare(ref x,ref y); //false

解决方法

最终的参考(没有双关语)在这里Equality Comparisons (C# Programming Guide).

你可以使用Object.ReferenceEquals来比较两个类型为T的对象的参考相等性if(而且只要我知道的话)T是一个引用类型.

正如Haedrian指出的那样,这个is not possible for value types even when they are passed by reference由于拳击在调用ReferenceEquals.

int x = 0,y = 0;
IsSameReference(ref x,ref x).Dump(); // Passing the same value type variable twice,by reference. We want a result of 'true'
IsSameReference(ref x,ref y).Dump(); // We expect 'false'

public static bool IsSameReference(ref int a,ref int b)
{
    return Object.ReferenceEquals(a,b);
}

两个调用都转储为false. (注意我重命名比较函数,因为它通常用于排序比较).

从本质上讲,T可以是任何类型,答案是否定的.

(带有int的乐趣和游戏仅从另一个答案取代的答案中删除).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐