C# 根据类型将 Class 实现接口转换为 Class

C# Casting a Class implementing interface to Class based on type

我的问题最好用一个例子来解释:

public IPlotModel MyPlotModel;
public ??? CastedModel;

public Constructor()
{
    MyPlotModel = new PlotModel(); //This should be interchangable with other types
                                   //E.g.: MyPlotModel = new OtherModel();
    CastedModel = (MyPlotModel.GetType()) MyPlotModel;
}

这基本上就是我想要的。 CastedModel 应该转换为 MyPlotModel 的类型。

我使用 Convert.ChangeType() 取得了一些成功。我设法将 CastedModel 的类型更改为正确的类型,但无法将 CastedModel 的值更改为 MyPlotModel。

这是我试过的:

Convert.ChangeType(CastedModel, MyPlotModel.GetType());
CastedModel = MyPlotModel;

但是 MyPlotModel 仍然被识别为接口,即使它被初始化为 PlotModel。

提前致谢, 亚历山大.

您似乎应该使用通用 class:

public class Example<TPlotModel> where TPlotModel : IPlotModel, new()
{
    public TPlotModel PlotModel { get; private set; }

    public Example()
    {
        this.PlotModel = new TPlotModel();
    }
}

然后您可以像这样实例化和使用它

var myExample = new Example<MyPlotModel>();
MyPlotModel foo = myExample.PlotModel;

棘手的部分是您必须在编译时知道正确的类型 - 没有其他地方可以理解。唯一的方法是使用泛型,正如@dav_i所建议的那样。

想想实例化应该如何工作——它是包装器 class 应该处理的东西(dav_i 的代码),还是应该从外部传递的东西?

您真的应该在包装器 class 之外处理 exact 类型吗?请记住,在使用接口时,不应根据接口的实际实现来区别对待 class(请参阅 OOP 中的 Liskov 替换原则和其他类似概念)。

你真的没有解释你所做事情背后的意图。你想在哪里使用实际类型?接口的意义何在?你想隐藏什么,又想暴露什么?