相关疑难解决方法(0)

重写System.Object.GetHashCode的最佳算法是什么?

在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?

.net algorithm hashcode gethashcode

1389
推荐指数
14
解决办法
19万
查看次数

为什么匿名类型的Equals实现比较字段?

我只是想知道为什么该语言的设计者决定在匿名类型上实现Equals,类似于Equals值类型.这不是误导吗?

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void ProofThatAnonymousTypesEqualsComparesBackingFields()
{
    var personOne = new { Name = "Pawe?", Age = 18 };
    var personTwo = new { Name = "Pawe?", Age = 18 };

    Console.WriteLine(personOne == personTwo); // false
    Console.WriteLine(personOne.Equals(personTwo)); // true
    Console.WriteLine(Object.ReferenceEquals(personOne, personTwo)); // false

    var personaOne = new Person { Name = "Pawe?", Age = 11 };
    var personaTwo = new …
Run Code Online (Sandbox Code Playgroud)

c# c#-3.0

55
推荐指数
4
解决办法
1万
查看次数

为什么ValueType.GetHashCode()实现得像?

ValueType.cs

**Action: Our algorithm for returning the hashcode is a little bit complex. We look 
**        for the first non-static field and get it's hashcode.  If the type has no 
**        non-static fields, we return the hashcode of the type. We can't take the
**        hashcode of a static member because if that member is of the same type as 
**        the original type, we'll end up in an infinite loop.

今天当我使用KeyValuePair作为字典中的键(它存储了xml属性名称(枚举)和它的值(字符串))时,我被它咬了,并期望它根据其所有字段计算它的哈希码,但根据实施情况,它只考虑了关键部分.

示例(来自Linqpad的c/p):

void Main()
{
    var kvp1 = …
Run Code Online (Sandbox Code Playgroud)

c# gethashcode

23
推荐指数
3
解决办法
7741
查看次数

ToString如何在匿名类型上工作?

我正在搞乱匿名类型,我不小心把它输出到控制台上.它看起来基本上是我如何定义它.

这是一个重现它的简短程序:

using System;
class Program
{
    public static void Main(string[] args)
    {
        int Integer = 2;
        DateTime DateTime = DateTime.Now;
        Console.WriteLine(new { Test = 0, Integer, s = DateTime });
        Console.ReadKey(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,输出是:

{ Test = 0, Integer = 2, s = 28/05/2013 15:07:19 }
Run Code Online (Sandbox Code Playgroud)

我尝试使用dotPeek进入程序集找出原因,但没有帮助.[1]这是dotPeek'd代码:

// Type: Program
// Assembly: MyProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// Assembly location: Not telling you! :P
using System;
internal class Program
{
  public static void Main(string[] args)
  {
    Console.WriteLine((object) new …
Run Code Online (Sandbox Code Playgroud)

.net c# anonymous-types tostring

21
推荐指数
3
解决办法
3470
查看次数

匿名类型的平等

当用于比较匿名类型时,为什么Equals()和==的语义不同?为什么要比较值和其他比较参考?它背后的原因是什么?

c# equality anonymous-types

6
推荐指数
1
解决办法
1526
查看次数