相关疑难解决方法(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万
查看次数

如何简化重复if-then-assign构造?

我有以下方法:

protected override bool ModifyExistingEntity(Product entity, ProductModel item)
{
    bool isModified = false;

    if (entity.Title != item.Title)
    {
        isModified = true;
        entity.Title = item.Title;
    }

    if (entity.ServerId != item.Id)
    {
        isModified = true;
        entity.ServerId = item.Id;
    }

    return isModified;
}
Run Code Online (Sandbox Code Playgroud)

我想知道你是否可以建议一种更好的方法来实现该方法.

问题很明显:每个属性有5行几乎复制粘贴的代码太多了.可能是我的愿景中使用Func-s/Expression-s 的解决方案.

.net c# lambda

48
推荐指数
6
解决办法
3446
查看次数

如何比较具有相似属性的两个截然不同的对象

这完全在C#中,使用.NET 2.0.

我有两个对象列表.它们不是相关对象,但它们确实具有可以比较的某些共同点,例如基于Guid的唯一标识符.这两个列表需要通过另一个列表进行过滤,该列表只包含Guid,它可能与前两个列表中包含的ID匹配,也可能不匹配.

我已经考虑过将每个对象列表转换为"对象"并按其排序的想法,但我不确定一旦它被转换我将能够访问ID属性,并且我认为该方法在知道要排序的列表是什么时,对这两个列表进行排序应该有些愚蠢.

引入每个对象列表的最佳方法是什么,以便可以仅使用ID来对列表进行排序?

c# architecture oop design-patterns

5
推荐指数
1
解决办法
6395
查看次数