Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为实现指定多个泛型类型_C#_Generics_Castle Windsor - Fatal编程技术网

C# 为实现指定多个泛型类型

C# 为实现指定多个泛型类型,c#,generics,castle-windsor,C#,Generics,Castle Windsor,鉴于以下服务结构: public interface IFoo { void Print(); } public class Foo<T> : IFoo { private T _item; public Foo(T item) { _item = item; } public void Print() { Console.WriteLine(_item); } } 公共接口IFo

鉴于以下服务结构:

public interface IFoo
{
    void Print();
}

public class Foo<T> : IFoo
{
    private T _item;

    public Foo(T item)
    {
        _item = item;
    }

    public void Print()
    {
        Console.WriteLine(_item);
    }
}
公共接口IFoo
{
作废打印();
}
公共类Foo:IFoo
{
私人信托基金项目;
公共食物(T项)
{
_项目=项目;
}
公开作废印刷品()
{
控制台写入线(_项);
}
}
除了显式地枚举它们之外,有没有其他方法可以用多种类型注册
Foo
组件?这是可行的,但我认为可能有更好的方法:

foreach (var t in myTypes)
{
    container.Register(Component.For<IFoo>()
        .ImplementedBy(typeof(Foo<>).MakeGenericType(new[] { t })));
}
foreach(myTypes中的var t)
{
container.Register(Component.For())
.ImplementedBy(typeof(Foo).MakeGenericType(new[]{t}));
}

您在
foreach type
循环中所做的是将打开的通用组件的数量减少到与
IFoo
相同的数量;有一种方法可以通过使用将其封装在干净的实现中,但此接口仅允许您使用一个签名关闭泛型类型;不能用多个类型关闭泛型类型

public class YourCustomGenericCloser: IGenericImplementationMatchingStrategy
{
   public Type[] GetGenericArguments(ComponentModel model, CreationContext context)
   {
      if(context.RequestedType == typeof(IFoo))
      {
         return typeof(TheDefaultTypeToCloseAgainst);
      }
      return null;
   }
}

我认为到目前为止,您的方法可能是针对基本接口注册具体泛型类型的更简单方法。

这段代码有什么问题?您想要什么样的改进?我原以为可能会有一个与
IGenericServiceStrategy
IGenericImplementationMatchingStrategy
相当的解决方案,但当您事先了解所有类型时,我还没有找到,这段代码很好,容器的每个
t
都有一个单独的组件,这更为明确@如果您想要一个组件,但在注册时不知道所有的
t
s,或者只是希望更具动态性,那么samy的实现是可取的。不过都很好。谢谢,我就是这么想的