c# - 类型比较未返回预期结果

标签 c# .net reflection comparison types

我使用以下代码比较类型,以便 DataContractSerializer 将在必要时使用正确的类型重新初始化。

    private void InitializeSerializer(Type type)
    {
        if (this.serializer == null)
        {
            this.serializer = new DataContractSerializer(type);
            this.typeToSerialize = type;
        }
        else
        {
            if (this.typeToSerialize != null)
            {
                if (this.typeToSerialize.GetType() != type.GetType())
                {
                    this.serializer = new DataContractSerializer(type);
                    this.typeToSerialize = type;
                }
            }
        }
    }

出于某种原因,当我比较这两种类型时,结果始终为真,我从不输入最终的“if”语句并重新初始化我的序列化程序。

我可以在比较处设置一个断点,可以清楚地看到这两种类型是 List<Host> (this.typeToSerialize.GetType()) 和 Post (type.GetType())

Host 和 Post 都有一个共同的祖先,但这不应该影响结果。

最佳答案

您正在 System.Type 上调用 GetType()。这将返回一个描述 System.Type 本身的 System.Type 对象。

这使得代码

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

相当于:

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

我猜你真正想做的是:

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

关于c# - 类型比较未返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3882196/

相关文章:

c# - 在 Entity Framework 中批量插入

c# - 如何获取当前属性的 PropertyDescriptor?

Java self 反射(reflection)

C# - 如何使用反射调用参数数量可变的静态方法

java - 如何使用带反射的动态加载界面?

c# - 具有非标准命名约定的数据库的 POCO 别名

c# - Visual Studio 一种显示运算符而不是文本的方法 示例 : ≠ instead of ! =

c# - CS8625 无法将空文字转换为 Interlocked.Exchange(ref c, null) 的不可空引用类型警告

.net - Entity Framework 和 .NET 4.0 的 LINQ to SQL 之间有什么区别?

.net - .NET 中字段初始值设定项的用途是什么(除了可读性)?