开发者

Type comparison not returning expected result

I am using the following code to compare types so that a DataContractSerializer will re-initialize with the correct type if necessary.

    private void InitializeSerializer(Type type)
    {
        if (this.serializer == null)
        {
            this.serializer = new DataContractSerializer(type);
            this.typeToSerialize = type;
        }
        else
        {
            if (this.typeToSerialize != null)
            {
                if (thi开发者_开发知识库s.typeToSerialize.GetType() != type.GetType())
                {
                    this.serializer = new DataContractSerializer(type);
                    this.typeToSerialize = type;
                }
            }
        }
    }

For some reason when I compare the two types the result is always true and I never enter the final 'if' statement and re-initialize my serialiser.

I can set a break point at the comparison and clearly see that the two types are List<Host> (this.typeToSerialize.GetType()) and Post (type.GetType())

Both Host and Post share a common ancestor but that shouldn't be affecting the result.


You are calling GetType() on a System.Type. This will return a System.Type object that describes System.Type itself.

This makes the code

if (this.typeToSerialize.GetType() != type.GetType())
{
   ...
}

equivalent to:

if(typeof(System.Type) != typeof(System.Type)) // Always false
{
   ... // Never enters here
}

I'm guessing what you really mean to be doing is:

if(typeToSerialize != type)
{
   ...
}


if (this.typeToSerialize != type)

looks more appropriate


It looks as though you are comparing the types of two Type objects. I think you would need to compare the type objects themselves.

this.typeToSerialize != type

Both this.typeToSerialize.GetType() and type.GetType() will return typeof(Type) (the same object).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜