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# – 比较两个托管引用所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)