简体   繁体   English

C#基于类型将类实现接口转换为Class

[英]C# Casting a Class implementing interface to Class based on type

My question is best explained with an example: 我的问题最好用一个例子来解释:

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;
}

This is basically what I want. 这基本上就是我想要的。 CastedModel should be cast to the type that MyPlotModel is. CastedModel应该转换为MyPlotModel的类型。

I've had some success using Convert.ChangeType(). 我使用Convert.ChangeType()取得了一些成功。 I manage to change the type of CastedModel to the correct type, but I can't manage to change the value of CastedModel to MyPlotModel. 我设法将CastedModel的类型更改为正确的类型,但我无法将CastedModel的值更改为MyPlotModel。

This is what I tried: 这是我试过的:

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

But MyPlotModel is still recognized as an interface even though it's initialized as a PlotModel. 但MyPlotModel仍然被识别为接口,即使它被初始化为PlotModel。

Thanks in advance, Alexander. 先谢谢,亚历山大。

This seems like you should use a generic class: 这似乎应该使用泛型类:

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

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

which you can then instantiate and use like 然后你可以实例化和使用

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

The tricky part is that you must know the correct type at compile-time - there's no other place where that would make sense. 棘手的部分是你必须在编译时知道正确的类型 - 没有其他地方可以理解。 The only way to do this is to use generics, as @dav_i suggested. 唯一的方法是使用泛型,如@dav_i建议的那样。

Think about how the instantiation should work - is it something the wrapper class should handle (dav_i's code), or is it something that should be passed from the outside instead? 想想实例化应该如何工作 - 包装类应该处理的东西(dav_i的代码),还是应该从外部传递的东西呢?

Are you really supposed to handle the exact type outside of the wrapper class? 你真的应该处理包装类之外的确切类型吗? Remember, when using an interface, you shouldn't treat it differently based on the actual class implementing the interface (look up Liskov's substitution principle and other similar concepts in OOP). 请记住,在使用接口时,不应该根据实现接口的实际类来区别对待(查看Liskov的替换原则和OOP中的其他类似概念)。

You're really not explaining anything about the intent behind what you're doing. 你真的没有解释你正在做的事情背后的意图。 Where do you want to use the actual type? 你想在哪里使用实际的类型? What's the point of the interface? 界面有什么意义? What are you trying to hide, and what do you want to expose? 你想隐藏什么,你想揭露什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM