나는 설명 할 수없는 매우 이상한 것을보고 있습니다. 내가 익숙하지 않은 C# 또는 런타임/이미 터의 버그를 예상하고있다. - 내가 내 DB에 존재하지 않는 알고 개체에 대한 true
을 반환 내 응용 프로그램을 테스트하는 동안null과의 비교는 expr == null과 expr! = null 모두에 대해 true로 평가됩니다.
public static bool HistoryMessageExists(DBContext context, string id)
{
return null != context.GetObject<HistoryMessage>(id);
}
, 나는이 오작동을 참조하십시오
나는 다음과 같은 방법이있다. 그래서 나는 방법에 멈춰 섰고, 즉시에, 나는 다음 실행 :
context.GetObject<HistoryMessage>(id)
null
null == context.GetObject<HistoryMessage>(id)
true
null != context.GetObject<HistoryMessage>(id)
true
GetObject
은과 같이 정의된다 : object
에 식을 캐스팅 할 때
public T GetObject<T>(object pk) where T : DBObject, new()
{
T rv = Connection.Get<T>(pk);
if (rv != null)
{
rv.AttachToContext(this);
rv.IsInserted = true;
}
return rv;
}
는 흥미롭게도, 비교가 제대로 평가를 :
null == (object)context.GetObject<HistoryMessage>(id)
true
null != (object)context.GetObject<HistoryMessage>(id)
false
동일성 연산자가 우선 적용되지 않습니다.
편집 : 연산자 오버로드가 잘못된 것으로 밝혀졌습니다. 그런데 내부 메소드 GetObject
에서 동등성이 올바르게 평가되는 이유는 rv
이이 경우 HistoryMessage
인 경우입니다.
public class HistoryMessage : EquatableIdentifiableObject
{
public static bool HistoryMessageExists(DBContext context, string id)
{
var rv = context.GetObject<HistoryMessage>(id);
bool b = rv != null;
return b;
}
public static void AddHistoryMessage(DBContext context, string id)
{
context.InsertObject(new HistoryMessage { Id = id });
}
}
public abstract partial class EquatableIdentifiableObject : DBObject, IObservableObject
{
public event PropertyChangedEventHandler PropertyChanged;
[PrimaryKey]
public string Id { get; set; }
//...
}
public abstract partial class EquatableIdentifiableObject
{
//...
public static bool operator ==(EquatableIdentifiableObject self, EquatableIdentifiableObject other)
{
if (ReferenceEquals(self, null))
{
return ReferenceEquals(other, null);
}
return self.Equals(other);
}
public static bool operator !=(EquatableIdentifiableObject self, EquatableIdentifiableObject other)
{
if (ReferenceEquals(self, null))
{
return !ReferenceEquals(other, null);
}
return !self.Equals(other);
}
}
public abstract class DBObject
{
[Ignore]
protected DBContext Context { get; set; }
[Ignore]
internal bool IsInserted { get; set; }
//...
}
여기 무슨 일이 일어나나요?
'HistoryMessage'가 항등 연산자를 구현합니까? –
@ LasseV.Karlsen 아니요, 무시하지 마세요. 여기에 운영자가 무시되지 않는다는 질문을 쓰는 것을 잊어 버렸습니다. –
'HistoryMessage'의 기본 클래스 중 하나에조차 없습니까? –