对此可能有一个简单的答案......但它似乎在逃避我.这是一个简化的例子:
public class Person
{
public string SocialSecurityNumber;
public string FirstName;
public string LastName;
}
Run Code Online (Sandbox Code Playgroud)
让我们说,对于这个特定的应用程序,如果社会安全号码匹配,并且两个名称都匹配,那么我们指的是同一个"人"是有效的.
public override bool Equals(object Obj)
{
Person other = (Person)Obj;
return (this.SocialSecurityNumber == other.SocialSecurityNumber &&
this.FirstName == other.FirstName &&
this.LastName == other.LastName);
}
Run Code Online (Sandbox Code Playgroud)
为了保持一致,我们还为团队中不使用该.Equals方法的开发人员覆盖==和!=运算符.
public static bool operator !=(Person person1, Person person2)
{
return ! person1.Equals(person2);
}
public static bool operator ==(Person person1, Person person2)
{
return person1.Equals(person2);
}
Run Code Online (Sandbox Code Playgroud)
好又花花公子,对吧?
但是,当Person对象发生时会发生什么null?
你不能写:
if (person == null)
{
//fail! …Run Code Online (Sandbox Code Playgroud) 这就是我在许多其他类继承的类中作为方法提出的.这个想法是它允许在相同类型的对象的属性之间进行简单比较.
现在,这确实有效 - 但为了提高我的代码质量,我想我会把它扔出去仔细检查.它怎么能更好/更有效/等等?
/// <summary>
/// Compare property values (as strings)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool PropertiesEqual(object comparisonObject)
{
Type sourceType = this.GetType();
Type destinationType = comparisonObject.GetType();
if (sourceType == destinationType)
{
PropertyInfo[] sourceProperties = sourceType.GetProperties();
foreach (PropertyInfo pi in sourceProperties)
{
if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
{
// if both are null, don't try to compare (throws exception)
}
else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
{
// only …Run Code Online (Sandbox Code Playgroud) 以下将导致==运算符重载方法的无限递归
Foo foo1 = null;
Foo foo2 = new Foo();
Assert.IsFalse(foo1 == foo2);
public static bool operator ==(Foo foo1, Foo foo2) {
if (foo1 == null) return foo2 == null;
return foo1.Equals(foo2);
}
Run Code Online (Sandbox Code Playgroud)
我如何检查空值?
我在当前项目中使用基于接口的编程,并在重载运算符(特别是Equality和Inequality运算符)时遇到问题.
更新 - 以下假设是错误的!
我担心要求使用Equals而不是operator ==的原因是我在.NET指南中找不到任何地方,它声称它会使用Equals而不是operator ==甚至建议它.但是,重新阅读覆盖等于和操作员指南后==我发现了这个:
默认情况下,operator ==通过确定两个引用是否指示同一对象来测试引用相等性.因此,引用类型不必实现operator ==以获得此功能.当一个类型是不可变的,也就是说,实例中包含的数据不能改变时,重载operator ==来比较值的相等而不是引用相等可能是有用的,因为作为不可变对象,它们可以被认为是相同的因为它们具有相同的价值.在非不可变类型中覆盖operator ==不是一个好主意.
和这个Equatable接口
当在Contains,IndexOf,LastIndexOf和Remove等方法中测试相等性时,IEquatable接口由泛型集合对象(如Dictionary,List和LinkedList)使用.它应该针对可能存储在泛型集合中的任何对象实现.
请参阅下面的代码和输出,以说明问题.
在使用基于接口的编程时,如何为类提供适当的操作符重载?
对于预定义的值类型,如果操作数的值相等,则相等运算符(==)返回true,否则返回false.对于除string之外的引用类型,如果其两个操作数引用同一对象,则==返回true.对于字符串类型,==比较字符串的值.
using System;
namespace OperatorOverloadsWithInterfaces
{
public interface IAddress : IEquatable<IAddress>
{
string StreetName { get; set; }
string City { get; set; }
string State { get; set; }
}
public …Run Code Online (Sandbox Code Playgroud) Object.GetHashCode()上的MSDN文档描述了该方法应该如何工作的3个矛盾规则.
规则1和3与我相矛盾.
Object.GetHashCode()是否根据对象的值或对象的引用返回唯一的数字.如果我覆盖方法,我可以选择使用什么,但我想知道内部使用的内容,如果有人知道的话.
有两个不可变类Base和Derived(派生自Base)我想定义Equality这样
平等总是多态的 - ((Base)derived1).Equals((Base)derived2)即将调用Derived.Equals
运营商==和!=将调用Equals,而不是ReferenceEquals(值相等)
我做了什么:
class Base: IEquatable<Base> {
public readonly ImmutableType1 X;
readonly ImmutableType2 Y;
public Base(ImmutableType1 X, ImmutableType2 Y) {
this.X = X;
this.Y = Y;
}
public override bool Equals(object obj) {
if (object.ReferenceEquals(this, obj)) return true;
if (obj is null || obj.GetType()!=this.GetType()) return false;
return obj is Base o
&& X.Equals(o.X) && Y.Equals(o.Y);
}
public override int GetHashCode() => HashCode.Combine(X, Y);
// boilerplate
public bool …Run Code Online (Sandbox Code Playgroud) namespace Dic
{
public class Key
{
string name;
public Key(string n) { name = n; }
}
class Program
{
static string Test()
{
Key a = new Key("A");
Key b = new Key("A");
System.Collections.Generic.Dictionary<Key, int> d = new System.Collections.Generic.Dictionary<Key, int>();
d.Add(a, 1);
return d.ContainsKey(b).ToString();
}
static void Main(string[] args)
{
System.Console.WriteLine(Test());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该改变什么才能成真?
你对写作平等检查的方法structs和classes创建?
1) "完全"平等检查是否需要多大的样板代码(如override Equals,override GetHashCode,通用Equals,operator==,operator!=)?
2)您是否明确指定您的类为IEquatable<T>接口建模?
3)我是否理解正确,没有实际的方法来自动应用Equals覆盖,当我调用类似的东西时a == b,我总是要实现Equals和operator==成员?
检查对象上的空引用的最有效方法是什么?我看过各种代码示例,它们有不同的检查方式,以便最有效或者被认为是最佳实践使用的方法如下:
Object.ReferenceEquals(item, null)
item == null
item != null
Object.Equals(item, null)
Run Code Online (Sandbox Code Playgroud)
谢谢
我有这样的课
public class TestData
{
public string Name {get;set;}
public string type {get;set;}
public List<string> Members = new List<string>();
public void AddMembers(string[] members)
{
Members.AddRange(members);
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有可能直接与这个类的实例进行比较,并发现它们完全相同?机制是什么?我正在寻找类似的东西if(testData1 == testData2) //Do Something,如果没有,怎么办呢?
c# ×10
.net ×5
object ×2
c#-7.0 ×1
c#-7.3 ×1
class ×1
comparison ×1
dictionary ×1
equality ×1
equals ×1
instance ×1
null ×1
overloading ×1
performance ×1
properties ×1