c# – 比较两个托管引用
发布时间:2020-12-16 02:03:48 所属栏目:百科 来源:网络整理
导读:如果它们相等,是否可以比较两个托管引用(类型为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,re
如果它们相等,是否可以比较两个托管引用(类型为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的乐趣和游戏仅从另一个答案取代的答案中删除). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |