问题描述
我一直以为DbNull.value是一个单例.因此,您可以执行以下操作:
I've always assumed that DbNull.value was a singleton. And thus you could do things like this:
VB.NET:
If someObject Is DbNull.Value Then
...
End if
C#:
If (someObject == DbNull.Value)
{
...
}
但是最近,我使用XmlSerialiser序列化了一个DbNull实例,突然不再是单例了.类型比较操作(例如C#(obj是DBNull))可以正常工作.
But recently, I serialised a DbNull instance using the XmlSerialiser and suddenly it wasn't a singleton any more. Type comparison operations (like C#'s (obj is DBNull)) work OK though.
代码如下:
[Serializable, System.Xml.Serialization.XmlInclude(typeof(DBNull))]
public class SerialiseMe
{
public SerialiseMe() { }
public SerialiseMe(object value)
{
this.ICanBeDbNull = value;
}
public Object ICanBeDbNull { get; set; }
}
public void Foo()
{
var serialiseDbNull = new SerialiseMe(DBNull.Value);
var serialiser = new System.Xml.Serialization.XmlSerializer(typeof(SerialiseMe));
var ms = new System.IO.MemoryStream();
serialiser.Serialize(ms, serialiseDbNull);
ms.Seek(0, System.IO.SeekOrigin.Begin);
var deSerialisedDbNull = (SerialiseMe)serialiser.Deserialize(ms);
// Is false, WTF!
var equalsDbNullDeserialised = deSerialisedDbNull.ICanBeDbNull == DBNull.Value;
// Is false, WTF!
var refEqualsDbNullDeserialised = object.ReferenceEquals(deSerialisedDbNull.ICanBeDbNull, DBNull.Value);
// Is true.
var convertIsDbNullDeserialised = Convert.IsDBNull(deSerialisedDbNull.ICanBeDbNull);
// Is true.
var isIsDbNullDeserialised = deSerialisedDbNull.ICanBeDbNull is DBNull;
}
为什么会这样?以及它是如何发生的?并可能在其他任何静态字段中发生吗?
Why is this the case? And how does it happen? And can it possibly happen with any other static fields?
PS:我知道VB代码示例正在进行参考比较,而c#正在调用Object.Equals.两者与DBNull的行为相同.我通常使用VB.
PS: I am aware the VB code sample is doing a reference comparison and c# is calling Object.Equals. Both have the same behaviour with DBNull. I usually work with VB.
推荐答案
尽管 DBNull.Value
是静态只读
,并且仅作为单个实例存在...反序列化后,序列化代码将根据流中的数据"创建类 DBNull
的新实例.由于 DBNull.Value
只是一个 DBNull
实例,因此序列化无法知道它是一个特殊"实例.
Although DBNull.Value
is a static readonly
and only exists as a single instance... when you de-serialize, the serialization code would be creating a new instance of the class DBNull
from the 'data' in the stream. Since the DBNull.Value
is simply a DBNull
instance, there is no way for serialization to know that it is a 'special' instance.
注意:
出于同样的原因,如果使用序列化然后反序列化的单例"实例创建自己的类,则将获得完全相同的行为.尽管反序列化实例将与原始实例没有区别,但它们不会是同一实例.
这篇关于当我使用XmlSerialiser反序列化DbNull时为什么不将它变成单身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!