mardi 22 septembre 2015

C# down-cast ComponentRegistration to non-generic type

I`m using Castle.Windsor library, and what i want is to get "Implementation" property, from all items in IRegistration[].

I have following interfaces and classes:

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

And a static class which contains this Components:

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

And of course variable a is null after every iteration. It works only when i cast to Generic ComponentRegistration

var a = registration as ComponentRegistration<A>;

But, that dont helps me if i have too much different components inside this array. So Switch statement is not an option. I have tried using reflections, but i still didn`t managed to properly cast.

How can i achieve what i want With or Without using reflections?

thxia.





Aucun commentaire:

Enregistrer un commentaire