c# – 比较两个托管引用

c# – 比较两个托管引用,第1张

概述如果它们相等,是否可以比较两个托管引用(类型为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;Compar 如果它们相等,是否可以比较两个托管引用(类型为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); //trueCompare(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的乐趣和游戏仅从另一个答案取代的答案中删除).

总结

以上是内存溢出为你收集整理的c# – 比较两个托管引用全部内容,希望文章能够帮你解决c# – 比较两个托管引用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1219286.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存