我想使用由另一个类实现的接口来调用函数,而无需在c#中创建该类的实例

时间:2019-04-20 13:04:50

标签: c# interface implementation

我想使用接口方法来调用所有函数,但是我不想创建实现该接口的类的实例。过去,我做了一些项目,其中我做了ISomeInterface proxy = ChannelFactory<SomeImplementation>().CreateChannel(),然后使用了proxy.Method()之类的接口方法。我想做这样的事情,如果可能的话可能没有ChannleFactory,我想知道是否有可能。

private static IUserInterface proxy;
        [STAThread]
        static void Main(string[] args)
        {
            bool closeApp = false;

            do
            {
                proxy.PrintMenu();

                int command;
                Int32.TryParse(Console.ReadKey().KeyChar.ToString(), out command);
                Console.WriteLine();
                closeApp = proxy.SendMenuCommand(command);
            } while (!closeApp);

            // Aplikacija ugasena
            Console.WriteLine("Application closed successfully. Press any key...");
            Console.ReadKey();
        }

弹出的错误是未将代理设置为对象的实例。

1 个答案:

答案 0 :(得分:4)

接口只是一个契约,它与实例无关。如果一个类实现了该接口,则可以将实例转换为该接口的类型,然后调用该接口中定义的方法/属性。。(它甚至不是代理)

该接口不包含任何实现。这是班级必须遵守的一组协议。

所以您必须有一个实例。

在您的示例中:proxy.PrintMenu();是谁实施了PrintMenu()

我可能是这样的:

界面:

// This is the contract. (as you can see, no implementation)
public interface IUserInterface
{
    void PrintMenu();
    bool SendMenuCommand(int command);
}

第一个实现:

// The class implements that interface, which it MUST implements the methods.
// defined in the interface.  (except abstract classes)
public class MyUserInterface : IUserInterface
{
    public void PrintMenu()
    {
        Console.WriteLine("1 - Option one");
        Console.WriteLine("2 - Option two");
        Console.WriteLine("3 - Option three");
    }

    public bool SendMenuCommand(int command)
    {
        // do something.
        return false;
    }
}

其他实施方式:

// same for this class.
public class MyOtherUserInterface : IUserInterface
{
    public void PrintMenu()
    {
        Console.WriteLine("1) Submenu 1");
        Console.WriteLine("2) Submenu 2");
        Console.WriteLine("3) Submenu 3");
    }

    public bool SendMenuCommand(int command)
    {
        // do something.
        return true;
    }
}

您的主要联系人:

private static IUserInterface menu;

[STAThread]
static void Main(string[] args)
{
    bool closeApp = false;

    // because the both classes implements the IUserInterface interface,
    // the both can be typecast to IUserInterface 
    IUserInterface menu = new MyUserInterface();

    // OR
    //IUserInterface menu = new MyOtherUserInterface();

    do
    {
        proxy.PrintMenu();

        int command;
        Int32.TryParse(Console.ReadKey().KeyChar.ToString(), out command);
        Console.WriteLine();
        closeApp = proxy.SendMenuCommand(command);
    } while (!closeApp);

    // Aplikacija ugasena
    Console.WriteLine("Application closed successfully. Press any key...");
    Console.ReadKey();
}