首页 > 解决方案 > 实现上的 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.");
        ...
    }
}

然而,这留下了执行期间出错的可能性。我想让参数的类型和返回值成为一个实现类。

最好的方法是什么?

标签: c#interfacecasting

解决方案


您可以创建一个泛型接口,使用其泛型类型的实现类:

public interface IModel<T> where T: IModel<T>
{
    T Apply(T from);
}

public class XxxModel: IModel<XxxModel>
{
    public XxxModel Apply(XxxModel from)  // All good
    {
    }
}

推荐阅读