相关疑难解决方法(0)

覆盖==运算符.如何比较null?

可能重复:
如何在没有无限递归的情况下检查'=='运算符重载中的空值?

对此可能有一个简单的答案......但它似乎在逃避我.这是一个简化的例子:

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)

.net c# null overloading operator-keyword

132
推荐指数
4
解决办法
6万
查看次数

比较c#中的对象属性

这就是我在许多其他类继承的类中作为方法提出的.这个想法是它允许在相同类型的对象的属性之间进行简单比较.

现在,这确实有效 - 但为了提高我的代码质量,我想我会把它扔出去仔细检查.它怎么能更好/更有效/等等?

/// <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)

c# comparison properties object

111
推荐指数
5
解决办法
15万
查看次数

如何在没有无限递归的'=='运算符重载中检查空值?

以下将导致==运算符重载方法的无限递归

    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)

我如何检查空值?

.net c# operator-overloading

110
推荐指数
4
解决办法
6846
查看次数

C#中基于接口的编程的运算符重载

背景

我在当前项目中使用基于接口的编程,并在重载运算符(特别是Equality和Inequality运算符)时遇到问题.


假设

  • 我正在使用C#3.0,.NET 3.5和Visual Studio 2008

更新 - 以下假设是错误的!

  • 要求所有比较使用Equals而不是operator ==不是一个可行的解决方案,尤其是在将类型传递给库(例如Collections)时.

我担心要求使用Equals而不是operator ==的原因是我在.NET指南中找不到任何地方,它声称它会使用Equals而不是operator ==甚至建议它.但是,重新阅读覆盖等于和操作员指南==我发现了这个:

默认情况下,operator ==通过确定两个引用是否指示同一对象来测试引用相等性.因此,引用类型不必实现operator ==以获得此功能.当一个类型是不可变的,也就是说,实例中包含的数据不能改变时,重载operator ==来比较值的相等而不是引用相等可能是有用的,因为作为不可变对象,它们可以被认为是相同的因为它们具有相同的价值.在非不可变类型中覆盖operator ==不是一个好主意.

和这个Equatable接口

当在Contains,IndexOf,LastIndexOf和Remove等方法中测试相等性时,IEquatable接口由泛型集合对象(如Dictionary,List和LinkedList)使用.它应该针对可能存储在泛型集合中的任何对象实现.


约束上

  • 任何解决方案都不能要求将对象从其接口转换为其具体类型.

问题

  • 当operator ==的两边都是接口时,底层具体类型的operator == overload方法签名都不匹配,因此将调用默认的Object operator ==方法.
  • 在类上重载运算符时,二元运算符的至少一个参数必须是包含类型,否则会生成编译器错误(错误BC33021 http://msdn.microsoft.com/en-us/library/watt39ff .aspx)
  • 无法在接口上指定实现

请参阅下面的代码和输出,以说明问题.


在使用基于接口的编程时,如何为类提供适当的操作符重载?


参考

==运算符(C#参考)

对于预定义的值类型,如果操作数的值相等,则相等运算符(==)返回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)

.net c# equals operator-overloading

72
推荐指数
1
解决办法
2万
查看次数

Object.GetHashCode()对引用或值是唯一的吗?

Object.GetHashCode()上的MSDN文档描述了该方法应该如何工作的3个矛盾规则.

  1. 如果两个相同类型的对象表示相同的值,则哈希函数必须为任一对象返回相同的常量值.
  2. 为获得最佳性能,哈希函数必须为所有输入生成随机分布.
  3. 无论对对象做出任何更改,哈希函数都必须返回完全相同的值.

规则1和3与我相矛盾.

Object.GetHashCode()是否根据对象的或对象的引用返回唯一的数字.如果我覆盖方法,我可以选择使用什么,但我想知道内部使用的内容,如果有人知道的话.

.net c#

24
推荐指数
2
解决办法
7817
查看次数

平等和多态

有两个不可变类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)

c# c#-7.0 c#-7.3

24
推荐指数
3
解决办法
966
查看次数

Dictionary.ContainsKey返回False,但想要True

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)

我应该改变什么才能成真?

.net c# dictionary

18
推荐指数
4
解决办法
2万
查看次数

C#等式检查

你对写作平等检查的方法structsclasses创建?

1) "完全"平等检查是否需要多大的样板代码(如override Equals,override GetHashCode,通用Equals,operator==,operator!=)?

2)您是否明确指定您的类为IEquatable<T>接口建模?

3)我是否理解正确,没有实际的方法来自动应用Equals覆盖,当我调用类似的东西时a == b,我总是要实现Equalsoperator==成员?

c# equality

10
推荐指数
2
解决办法
4555
查看次数

空引用检查的好习惯是什么?

检查对象上的空引用的最有效方法是什么?我看过各种代码示例,它们有不同的检查方式,以便最有效或者被认为是最佳实践使用的方法如下:

Object.ReferenceEquals(item, null)

item == null

item != null

Object.Equals(item, null)
Run Code Online (Sandbox Code Playgroud)

谢谢

c# performance

9
推荐指数
3
解决办法
2万
查看次数

比较一个类的两个实例

我有这样的课

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# class object instance

9
推荐指数
3
解决办法
5万
查看次数