How can I draw an object dynamically?

I am sure that this was asked earlier, but, unfortunately, the only thing I found was this one , which was not a solution for me. In my current project, I am doing something like:

private object obj;

private void Initialize()
{
    obj.Initialize();
}

private void CreateInstanceA()
{
    obj = Activator.CreateInstance(typeof(MyClassA));
}

private void CreateInstanceB()
{
    obj = Activator.CreateInstance(typeof(MyClassB));
}

This code does not work, of course, because I did not use it obj, because its type changes dynamically.

How can I use it dynamically?

+5
source share
2 answers

Three options:

  • If you control both classes, and you can force them to implement a common interface that includes everything you need, then do it - and drop it to the interface
  • # 4 .NET 4, - private dynamic obj;,
  • , .

, , , - ... .

, , , .

+9

, CreatInstanceB() MyClassB, ?

:

((MyClassA)obj).Initialize();

...

((MyClassB)obj).Initialize();

, Initialize obj .

0

All Articles