简体   繁体   English

如何初始化一个继承接口的类?

[英]How to initalize a class that inherits interface?

I'm trying to apply SOLID in my code.我正在尝试在我的代码中应用SOLID I've got a Menu with several options.我有一个有几个选项的菜单。 Every menu has some buttons.I'm making a Interface for the first menu buttons:每个菜单都有一些按钮。我正在为第一个菜单按钮制作一个Interface

interface IConvertToPartListButton
{
    void ConvertToPartList();
}
class BtnConvertToPartList : IConvertToPartListButton
{
   void ConvertToPartList()
   {
        //Do something
   } 
}

After that I implement an interface that inherits those two buttons I created之后,我实现了一个接口,该接口inherits了我创建的那两个按钮

interface IImportPartsButtons : IConvertToPartListButton,IDeleteIP
{
}

So for every menu I will do that.所以对于每个菜单,我都会这样做。 After that I want to inherit all menu buttons :之后我想继承所有菜单按钮:

interface IButton : IImportPartsButtons,SecondMenuButtons,ThirdMenuButtons
{
}

When I try to make a new instance of the class BtnConverToPartList it's not possible.当我尝试创建类BtnConverToPartList的新实例时,这是不可能的。

 public static IButton GetButton() => new BtnConvertToPartList();

Error:错误:

Cannot implicitly convert type 'MOSOSoftware.BtnConvertToPartList' to 'MOSOSoftware.IButton'.

If I am doing something wrong please write that down, I'm new to programming and I'm still learning.如果我做错了什么,请写下来,我是编程新手,我仍在学习。 Thank You!谢谢你!

You are doing wrong inheritance.你在做错误的继承。 "BtnConvertToPartList" implements "IConvertToPartListButton" but "IButton" is not "IConvertToPartListButton" until you implement "IButton" to "IConvertToPartListButton". “BtnConvertToPartList”实现“IConvertToPartListButton”但“IButton”不是“IConvertToPartListButton”,直到你实现“IButton”到“IConvertToPartListButton”。 Please find the changed code below,请在下面找到更改后的代码,

 interface IConvertToPartListButton : IButton
{
    void ConvertToPartList();
}


interface IImportPartsButtons : IConvertToPartListButton
{
}

interface IButton
{
}

class BtnConvertToPartList : IConvertToPartListButton
{
    public void ConvertToPartList()
    {
        //Do something
    }
}

and the instatntiation,和实例化,

public static IButton GetButton() => new BtnConvertToPartList();

Now it should work because BtnConvertToPartList is IButton as well because IButton is IConvertToPartListButton.现在它应该可以工作了,因为 BtnConvertToPartList 也是 IButton,因为 IButton 是 IConvertToPartListButton。

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

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