我正在尝试为我构建的新类型定义自定义相等方法。这是一个MWE,正在努力实现我的目标。
public override int SaveChanges ( ) {
var lastSeq = this.[yourTable].OrderByDescending ( c => c.Seq ).FirstOrDefault ( ).RefSeq;
foreach(var ent in this.ChangeTracker.Entries ( ).Where ( x => x.Entity is [theClassofYourEntity] ) ) {
( ( [ theClassofYourEntity ] ) ent.Entity ).RefSeq = lastSeq;
}
return base.SaveChanges ( );
}
然后我收到类似mutable struct a
first_num::Int
second_num::Int
end
import Base.==
import Base.hash
function hash(obj::a, h=33141651)
return hash((obj.first_num, obj.second_num), h)
end
function ==(obj1::a, obj2::a)
if hash(obj1) == hash(obj2)
return true
else
return false
end
end
a1 = a(2,3)
a2 = a(2,3)
a1 == a2
是否会成为Int64?
此外,如果对属性元组进行散列并不是正确的方法,请告诉我。
编辑:实际上,我跑了这个,我得到了ERROR: TypeError: ==: in typeassert, expected UInt64, got Int64
。 MethodError: no method matching hash(::Tuple{Int64,Int64}, ::Int64)
是否被提升为Int64?
答案 0 :(得分:3)
问题是h
(33141651)的字面值是Int
而不是UInt
。因此,当您使用元组hash
调用h
时,Int
为hash
,但内部元组UInt
函数需要h
。我根本不认为你必须为function Base.hash(obj::a, h::UInt)
return hash((obj.first_num, obj.second_num), h)
end
指定一个值,这样的事情就足够了:
mutable struct A
first::Int
second::Int
end
function Base.hash(obj::A, h::UInt)
return hash((obj.first, obj.second), h)
end
function Base.:(==)(obj1::A, obj2::A)
return hash(obj1) == hash(obj2)
end
完整性的完整示例:
julia> a = A(2,3); b = A(2,3)
A(2, 3)
julia> hash(a)
0x965b43497b212144
julia> hash(b)
0x965b43497b212144
julia> a == b
true
具有以下行为
Picasso