简体   繁体   English

C# 调用在许多类中实现的接口方法而没有这些类的实例

[英]C# call interface method implemented in many classes without having instance to those classes

Sample Code示例代码
using System;

public interface MyInterface
{
    void MyMethod();
}

public class A:MyInterface
{
    void MyInterface.MyMethod()
    {
        Console.WriteLine("Hello World from A");
    }
}

public class B:MyInterface
{
    void MyInterface.MyMethod()
    {
        Console.WriteLine("Hello World from B");
    }
}

public class C:MyInterface
{
    void MyInterface.MyMethod()
    {
        Console.WriteLine("Hello World from C");
    }
}

public class Program
{
    public static void Main()
    {
        C obj = new C();
        MyInterface iface=(MyInterface)obj;
        iface.MyMethod(); // This will print "Hello World from C"
    }
}
The Problem问题

The Sample code I given above shows the method I used for calling interface method in my project, In the code I have an interface called MyInterface and it has a method called MyMethod() , In current sample I called the interface method using object of Class C , In my project I will have more classes that needs to implement MyInterface and the My method in all these classes need to be called at once.我上面给出的示例代码显示了我在项目中调用接口方法所使用的方法,在代码中我有一个名为MyInterface的接口,它有一个名为MyMethod()的方法,在当前示例中,我使用 Class 的 object 调用了接口方法C ,在我的项目中,我将有更多的类需要实现 MyInterface 并且需要立即调用所有这些类中的 My 方法。

Take an Example举个例子

Currently I have classes A,B,C and all of them have MyMethod() with Different function body, then later I added another class D and I need to call MyMethod() in all classes at the same time, the number of classes might be 100's, so is there any way to call all MyMethod() without creating object for 100's of classes.目前我有 A、B、C 类,它们都有MyMethod()和不同的 function 主体,后来我又添加了另一个 class D,我需要同时在所有类中调用MyMethod() ,类的数量可能是 100 个,所以有没有办法调用所有MyMethod()而无需为 100 个类创建 object。

A possible solution is to use Polymorphism .一种可能的解决方案是使用 多态性 You can have a method like this:你可以有这样的方法:

public static void ExecuteMyMethods(IEnumerable<MyInterface> instances)
{
    foreach(var instance in instances) instance.MyMethod();
}

It will be working for you as needed and you will not have to modify it when new implementation of MyInterface occurs.它将根据需要为您工作,并且在 MyInterface 的新实现出现时您不必修改它。 You will have to pass the new instance from the caller side.您将必须从调用方传递新实例。

You can also wrap & isolate the logic of getting the collection of MyInterface implementations somewhere, to have it in a single place & once new implementation comes around, you will know where to create an instance of it, for this method to work properly.您还可以包装和隔离在某处获取MyInterface实现集合的逻辑,将其放在一个地方,一旦出现新的实现,您就会知道在哪里创建它的实例,以便此方法正常工作。 You can consider using Factory method pattern for that.您可以考虑为此使用工厂方法模式

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

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