首页 > 解决方案 > 为什么我收到警告无法将一种类型转换为另一种类型?

问题描述

我有这个方法:

public TYPE GetObjBy<TYPE>() where TYPE : BaseConfiguration
{
  Type type = typeof(TYPE);

  if (type == typeof(MCConfiguration))
  {
    return (TYPE) new MCConfiguration(); <--- This line I get an error
  }

  return (TYPE) new BaseConfiguration(); <-- This line is OK
}

MCConfigurationextends from BaseConfiguration,但在一行中我得到一个错误,但在另一行中没有。这怎么可能?

编辑

使用

ConfigurationParser par = new ConfigurationParser("");
MCConfiguration config = par.GetObjBy<MCConfiguration>();

编辑

        public TYPE GetObjBy<TYPE>() where TYPE : BaseConfiguration, new()
        {
            Type type = typeof(TYPE);
            BaseConfiguration config;

            if (type == typeof(MCConfiguration))
            {
                config = new MCConfiguration();
            }
            else
            {
                config = default(TYPE);
            }

            return (TYPE)config;
        }

标签: c#

解决方案


您收到此错误是因为GetObjBy<>方法可用于从以下派生的任何类型BaseConfiguration

class MappingSchemaTest : BaseConfiguration
{}

class MappingSchemaTestImpl : BaseConfiguration
{
    T GetObjBy<T>() where T : BaseConfiguration
    {
        return new MappingSchemaTestImpl();
    }

    void Use()
    {
        var t = GetObjBy<MappingSchemaTest>();
    }
}

两者MappingSchemaTestMappingSchemaTestImpl来自BaseConfiguration

但是return new MappingSchemaTestImpl();无法返回,因为MappingSchemaTest通用参数与MappingSchemaTestImpl

PSnew()在泛型参数上添加约束并写成

    T GetObjBy<T>() where T : BaseConfiguration, new()
    {
        return new T();
    }

PPS 另一种选择是不返回泛型,而是返回基类或接口,例如

    BaseConfiguration GetObjBy<T>() where T : BaseConfiguration
    {
        if (true)
                return new MCConfiguration();
        else
                return new MCConfiguration2();
    }

推荐阅读