【发布时间】:2020-07-15 12:30:46
【问题描述】:
我想在 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.");
...
}
}
但是,这会在执行期间留下错误的可能性。 我想让参数的类型和返回值成为一个实现类。
最好的方法是什么?
【问题讨论】: