简体   繁体   English

可“实施N次”的界面设计

[英]Design for interface that can be “implemented N times”

Currently I'm using a generic interface to declare IoC dependencies like this: 目前,我正在使用通用接口来声明IoC依赖关系,如下所示:

public interface IComposition<T>
{
  T Dependency { get; set; }
}

But happens that my implementations could have more than one dependency at same time. 但是碰巧我的实现可能同时具有多个依赖关系。

I know it's ridiculous, but just to you guys understand what I need... let's say I implement the interface multiple times to solve my problem: 我知道这很荒谬,但是只是为了让你们了解我需要的东西。假设我多次实现了该接口来解决我的问题:

public class MyClass : IComposition<TypeA>, IComposition<TypeB>
{
  ...
}

I believe that using IComposition<T1, T2, ...> or one ITypeXDependent for each type aren't good options. 我相信对每种类型使用IComposition<T1, T2, ...>或一个ITypeXDependent都不是很好的选择。 My core needs to resolve dependencies at runtime using reflection. 我的核心需要在运行时使用反射来解决依赖关系。 So, thats why I'm not passing dependencies through the constructor. 因此,这就是为什么我没有通过构造函数传递依赖项的原因。

Does anyone know some trick that can help me out? 有谁知道一些可以帮助我的把戏?

I would use constructor parameters instead of your current scheme to set up dependencies: 我将使用构造函数参数而不是当前方案来设置依赖关系:

public class MyClass
{
    public void MyClass(TypeA a, TypeB b)
    {
        ....
    }
}

Aside regular interfaces, generic interfaces can be "implemented N times" since each generic type parameter used create another interface type . 除了常规接口之外,通用接口可以“实现N次”,因为使用的每个通用类型参数都会创建另一个接口类型 The only thing to care about is to implement the interface explicitly: 唯一需要注意的是显式实现接口:

public interface IComposition<T>
{
    T Dependency { get; set; }
}

public class MyClass: IComposition<TypeA>, IComposition<TypeB>
{
    IComposition<TypeA>.TypeA Dependency { get; set; }
    IComposition<TypeB>.TypeB Dependency { get; set; }
}

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

相关问题 我如何在 inheritance 链中多次实现该接口的同时显式实现该接口? - How can i explicitly implement an interface while having implemented that interface multiple times in inheritance chain? 访问在类层次结构中多次实现的接口 - Accessing interface that is implemented multiple times in the class hiararchy 这个COM接口可以用C#实现吗? - Can this COM interface be implemented in C#? 接口可以要求实现基类吗? - Can an interface require a base class to be implemented? 你能模拟一个只能实现它的后代的界面吗? - Can you model an interface where only it's descendants can be implemented? 为什么不能使用持有实现接口的具体类型的属性来实现持有接口类型的接口属性? - Why can interface properties holding an interface type not be implemented with a property holding a concrete type that implements the interface? 如何限制仅由通用类型实现的接口 - How can I restrict an Interface to be implemented by only a generic type 如何在运行时确定是否实现了接口成员? - How can I determine at runtime if an interface member is implemented? 如何定义可以在c#中实现的异步f#接口? - How to define an async f# interface that can be implemented in c#? 如何测试.NET中实现的COM接口? - How can I test a COM interface implemented in .NET?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM