【问题标题】:C# Interface Type Convertion on Implements实现上的 C# 接口类型转换
【发布时间】: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.");
        ...
    }
}

但是,这会在执行期间留下错误的可能性。 我想让参数的类型和返回值成为一个实现类。

最好的方法是什么?

【问题讨论】:

    标签: c# interface casting


    【解决方案1】:

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

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

    【讨论】:

    • 感谢 Sinatr,John Alexiou!
    • 它工作正常。我没想到它会在几秒钟内起作用!
    • T 视为派生类型。 T 是实现接口的任何类型。
    猜你喜欢
    • 2015-05-18
    • 2017-02-16
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 2013-07-22
    相关资源
    最近更新 更多