c# - 将 ComponentRegistration 向下转换为非泛型类型

标签 c# generics reflection casting castle-windsor

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

我有以下接口(interface)和类:

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);
      }
    }
  }

当然变量 a 在每次迭代后都是 null。 仅当我转换为 Generic ComponentRegistration 时它才有效

var a = registration as ComponentRegistration<A>;

但是,如果我在这个数组中有太多不同的组件,这对我没有帮助。所以 Switch 语句不是一个选项。 我尝试过使用反射,但仍然无法正确转换。

使用或不使用反射如何实现我想要的目标?

谢谢。

最佳答案

这并不容易,因为 IRegistration API 从来就不是为了以这种方式使用的。

所以我的回答分为两部分。

  1. 如何做到这一点。使用动态

您只需要更改一小部分代码:

foreach (dynamic registration in list)
{
  Console.WriteLine(registration.Implementation.FullName);
}
  • 您想要实现的根本目标是什么?如果您的目标是对注册内容、注册方式保持一定程度的可见性并留意潜在问题,请查看 Windsor 的诊断程序。
  • 关于c# - 将 ComponentRegistration 向下转换为非泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32710444/

    相关文章:

    c# - 如何使用 OleDbDataAdapter 从 Excel 文件中的任何电子表格中进行选择

    generics - 如何调用像 std::num::Float::epsilon() 这样的静态特征方法?

    c# - 如何约束多个泛型类型?

    C# - 反射 - 基本属性

    C# 反射获取嵌套属性类型中 GetValues 的对象

    c# - 为对象类型添加值 c#

    c# - ASP.NET - 发生异常时发送电子邮件

    c# - 安装程序无法删除以前的版本

    java - 为什么 Java 必须采用类型删除来保持向后兼容性?

    c# - 调用使用Using语句打开的子表单的方法