c# - 为什么我收到警告无法将一种类型转换为另一种类型?
问题描述
我有这个方法:
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
}
MCConfiguration
extends 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;
}
解决方案
您收到此错误是因为GetObjBy<>
方法可用于从以下派生的任何类型BaseConfiguration
:
class MappingSchemaTest : BaseConfiguration
{}
class MappingSchemaTestImpl : BaseConfiguration
{
T GetObjBy<T>() where T : BaseConfiguration
{
return new MappingSchemaTestImpl();
}
void Use()
{
var t = GetObjBy<MappingSchemaTest>();
}
}
两者MappingSchemaTest
都MappingSchemaTestImpl
来自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();
}
推荐阅读
- camunda - 运行时和历史的分离
- angular - 如何将 Angular 语言环境日期转换为 API 使用的正确日期格式?
- android - 从android项目构建jar文件时任务':app:kaptGenerateStubsDebugKotlin'的执行失败
- ios - 在 B2B 应用程序中支持第三方支付方式
- angular - Internet Explorer 中的“无法将对象转换为原始值”
- android - Google Play Billing 2.0 测试待处理交易和确认
- react-native - ReactNative:组件中的统一参数使用可能吗?
- r - ggplot() 的可变行限制
- php - 如何将最后一个插入 id 数据发送到另一个函数?
- javascript - 未捕获的类型错误:无法读取未定义的属性“str”