相关疑难解决方法(0)

正确的方法来重写Equals()和GetHashCode()

我之前从未真正这样做过,所以我希望有人可以告诉我正确实现我的类的Except()和GetHashCode()的重写.

我正在尝试修改类,以便我可以使用LINQ Except()方法.

public class RecommendationDTO{public Guid RecommendationId { get; set; }
public Guid ProfileId { get; set; }
public Guid ReferenceId { get; set; }
public int TypeId { get; set; }
public IList<TagDTO> Tags { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool IsActive { get; set; }
public object ReferencedObject { get; set; }
public bool IsSystemRecommendation { get; set; }
public int VisibilityScore { get; …
Run Code Online (Sandbox Code Playgroud)

c# equality gethashcode

94
推荐指数
3
解决办法
12万
查看次数

C# - 值类型等于方法 - 为什么编译器使用反射?

我只是遇到了一些非常奇怪的东西:当你在一个值类型上使用Equals()方法时(如果这个方法当然没有被覆盖)你会得到一些非常慢的东西- 使用一对一比较字段反思!如:

public struct MyStruct{
   int i;
}

   (...)

   MyStruct s, t;
   s.i = 0;
   t.i = 1;
   if ( s.Equals( t ))   /*  s.i will be compared to t.i via reflection here. */
      (...)
Run Code Online (Sandbox Code Playgroud)

我的问题:为什么C#编译器不生成比较值类型的简单方法?像(在MyStruct的定义中):

   public override bool Equals( Object o ){
      if ( this.i == o.i )
         return true;
      else
         return false;
   }
Run Code Online (Sandbox Code Playgroud)

编译器在编译时知道MyStruct的字段是什么,为什么它要等到运行时才能枚举MyStruct字段?

对我来说很奇怪.

谢谢 :)

补充:对不起,我只是意识到,当然,Equals它不是语言关键字而是运行时方法......编译器完全不知道这种方法.所以在这里使用反射是有意义的.

c# compiler-construction struct

16
推荐指数
2
解决办法
6782
查看次数