【问题标题】:Down-cast ComponentRegistration to non-generic type将 ComponentRegistration 向下转换为非泛型类型
【发布时间】:2015-09-22 07:05:15
【问题描述】:

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

我有以下接口和类:

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 在每次迭代后都为空。 它仅在我转换为 Generic ComponentRegistration 时才有效

var a = registration as ComponentRegistration<A>;

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

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

thxia。

【问题讨论】:

  • 我猜您要解决的实际问题不仅仅是将所有注册写入控制台?如果没有,您能否分享您要解决的实际问题是什么?可能有不同的方法。
  • 我需要从此组件中导出所有“实施”属性。这应该以非硬编码方式完成

标签: c# generics reflection casting castle-windsor


【解决方案1】:

这并不容易,因为 IRegistration API 从来没有打算以这种方式使用。

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

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

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

foreach (dynamic registration in list)
{
  Console.WriteLine(registration.Implementation.FullName);
}
  1. 您要在这里实现的基本目标是什么?如果您的目标是在一定程度上了解注册内容、注册方式以及注意潜在问题,请查看 Windsor 的诊断信息。

【讨论】:

    【解决方案2】:

    少量的Reflection就解决了问题(量不大,但是看起来很冗长,因为Reflection):

    foreach (var registration in list)
    {
      Console.WriteLine(
             ((Type)registration.GetType().GetProperty(
                    "Implementation"
             ).GetGetMethod().Invoke(
                    registration,new object[] { })
             ).FullName);
    }
    

    由于在运行时之前您不会知道用作泛型类型参数的类型,所以我认为没有任何反射没有办法做到这一点。


    以上假设所有注册是某种ComponentRegistration&lt;T&gt;对象。如果这是一个不安全的假设,那么 IRegistration 的其他一些实现可能没有实现 Implementation 属性,或者它可能无法公开访问 - 如果是这种情况,请插入适当的临时错误检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多