繁体   English   中英

向下注册ComponentRegistration为非通用类型

[英]Down-cast ComponentRegistration to non-generic type

我正在使用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);
      }
    }
  }

当然,每次迭代后变量a为null。 它仅在我强制转换为通用ComponentRegistration时有效

var a = registration as ComponentRegistration<A>;

但是,如果我在此数组中有太多不同的组件,那对我没有帮助。 因此,Switch语句不是一个选择。 我已经尝试过使用反射,但是我仍然没有设法正确投射。

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

thxia。

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

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

  1. 您该怎么做。 使用dynamic

您只需要更改一点代码即可:

foreach (dynamic registration in list)
{
  Console.WriteLine(registration.Implementation.FullName);
}
  1. 您要在这里实现的基本目标是什么? 如果您的目标是保持对注册内容,如何以及如何发现潜在问题的了解,请查看温莎的诊断程序。

少量的Reflection解决了这个问题(虽然数量很少,但是看起来很冗长,因为Reflection):

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

由于直到运行时您才知道用作通用类型参数的类型,所以我认为没有任何反思就无法实现这一点。


上述假设所有的注册的ComponentRegistration<T>某种物体。 如果这是不安全的假设,则可能有IRegistration其他一些实现未实现Implementation属性,或者它可能无法公开访问-因此,请插入适当的临时错误检查。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM