C# 向下转换组件注册为非泛型类型

C# 向下转换组件注册为非泛型类型,c#,generics,reflection,casting,castle-windsor,C#,Generics,Reflection,Casting,Castle Windsor,我正在使用Castle.Windsor库,我想要的是从IRegistration[]中的所有项中获取“Implementation”属性 我有以下接口和类: public interface IA { int a { get; set; } } public class A : IA { public int a { get; set; } } public interface IB { int b { get; set; } }

我正在使用Castle.Windsor库,我想要的是从IRegistration[]中的所有项中获取“Implementation”属性

我有以下接口和类:

public interface IA
  {
    int a { get; set; }
  }

  public class A : IA
  {
    public int a { get; set; }
  }

  public interface IB
  {
    int b { get; set; }
  }

  public class B : IB
  {
    public int b { get; set; }
  }
以及包含以下组件的静态类:

  public static class Bootekstraperek
  {
    private static readonly IRegistration[] _commonRegistrations =
    {
      Component.For<IA>().ImplementedBy<A>(),
      Component.For<IB>().ImplementedBy<B>()
    };

    public static void Test()
    {
      List<IRegistration> list = _commonRegistrations.ToList();

      foreach (var registration in list)
      {
        ComponentRegistration a = registration as ComponentRegistration;
        Console.WriteLine(a.Implementation.FullName);
      }
    }
  }
公共静态类Bootekstraperek
{
私有静态只读IRegistration[]\u commonRegistrations=
{
Component.For().ImplementedBy(),
Component.For().ImplementedBy()实现
};
公共静态无效测试()
{
列表=_commonRegistrations.ToList();
foreach(列表中的var注册)
{
ComponentRegistration a=注册为ComponentRegistration;
Console.WriteLine(a.Implementation.FullName);
}
}
}
当然,变量a在每次迭代后都是空的。 它仅在转换为泛型ComponentRegistration时起作用

var a = registration as ComponentRegistration<A>;
var a=注册为组件注册;
但是,如果我在这个数组中有太多不同的组件,这对我没有帮助。所以Switch语句不是一个选项。 我试过使用反射,但还是没能正确地投射

我如何在使用或不使用反射的情况下实现我想要的


thxia.

少量的反射可以解决问题(这是少量的,但看起来很冗长,因为反射):

因为在运行时之前您不知道哪些类型被用作泛型类型参数,所以我认为没有任何方法可以在不进行任何反射的情况下做到这一点



以上假设所有注册都是某种类型的
ComponentRegistration
对象。如果这是一个不安全的假设,可能还有其他一些
IRegistration
的实现没有实现
实现
属性,或者它可能不可公开访问-因此,如果是这种情况,请插入适当的临时错误检查。

这并不容易,因为
IRegistration
API从未打算以这种方式使用

所以我的答案有两部分

  • 你怎么能做到。使用
    动态
  • 您只需更改一小部分代码:

    foreach (dynamic registration in list)
    {
      Console.WriteLine(registration.Implementation.FullName);
    }
    
  • 你在这里想要达到的基本目标是什么?如果您的目标是保持对注册内容、注册方式和潜在问题的可见性,请查看温莎诊断

  • 我猜您试图解决的实际问题不仅仅是将所有注册写入控制台?如果没有,你能分享一下你试图解决的实际问题是什么吗?可能有不同的方法。我需要从这个组件导出所有“实现”属性。这应该以非硬编码的方式完成
    foreach (dynamic registration in list)
    {
      Console.WriteLine(registration.Implementation.FullName);
    }