c# - 实现上的 C# 接口类型转换
问题描述
我想在 C# 实现中转换接口定义的类型。
前任):
public interface IModel
{
IModel Apply(IModel from);
}
public class XxxModel: IModel
{
public XxxModel Apply(XxxModel from) // <- Interface Implementation Error
{
}
}
作为对策:
public class XxxModel: IModel
{
public IModel Apply(IModel from)
{
if (from.GetType() != typeof(XxxModel))
throw new ArgumentException("Type Not Matched.");
...
}
}
然而,这留下了执行期间出错的可能性。我想让参数的类型和返回值成为一个实现类。
最好的方法是什么?
解决方案
您可以创建一个泛型接口,使用其泛型类型的实现类:
public interface IModel<T> where T: IModel<T>
{
T Apply(T from);
}
public class XxxModel: IModel<XxxModel>
{
public XxxModel Apply(XxxModel from) // All good
{
}
}
推荐阅读
- node.js - 是否可以批量读取mongoDB?
- sql - 即使在 where in 子句中的条件为空,如何返回结果集
- html - 通过achor标签从chrome打开firefox?
- c - Uncrustify:如何在声明或分配变量之前添加新行?
- sql-server - 在使用 CASE 或 CHOOSE 等条件函数时,如何确定每位员工的加班时间?
- javascript - SwiperJS - 使用函数初始化后禁用幻灯片
- javascript - 即使与应用程序建立连接,Mongodb Atlas 集合中也没有收到数据
- c++ - 为什么我在STM32上不能通过SPI读取寄存器?
- css - 以正确的方式增加模式中的 Bootstrap 4 标签宽度
- javascript - 如何在一行 html 中包含 2 个段落