Currently, I have code like this:
static void Main()
{
int whichClass = 0;
if (whichClass == 0)
{
//repeat code
TestAbstract clTest = new ClassA();
clTest.MainFunc();
}
else if (whichClass == 1)
{
//repeat code
TestAbstract clTest = new ClassB();
clTest.MainFunc();
}
else if (whichClass == 10)
{
//repeat code
TestAbstract clTest = new ClassX();
clTest.MainFunc();
}
}
As you see, I have to write code 3 times for initial and call function at 3 different classes.
What I want is we just call 1 time with dynamic class. How can it is possible?
Well, you could have a Dictionary<int, Type>, or a Dictionary<int, Func<TestAbstract>:
var typeMapping = new Dictionary<int, Type>
{
{ 0, typeof(ClassA) },
{ 1, typeof(ClassB) },
{ 10, typeof(ClassX) }
};
...
Type type;
if (typeMapping.TryGetValue(whichClass, out type))
{
TestAbstract test = (TestAbstract) Activator.CreateInstance(type);
test.MainFunc();
}
Using a Func<TestAbstract> would give more flexibility for how you created the TestAbstract instances, and provide more compile-time type safety, but be more long-winded:
var factoryMapping = new Dictionary<int, Func<TestAbstract>>
{
{ 0, () => new ClassA() },
{ 1, () => new ClassB() },
{ 10, () => new ClassX() }
};
...
Func<TestAbstract> factory;
if (factoryMapping.TryGetValue(whichClass, out factory))
{
TestAbstract test = factory();
test.MainFunc();
}
It's not clear where the integer values are coming from, by the way - you might want an enum for that. Heck, the enum names could even be the names of the types:
TestClass whichClass = TestClass.ClassA;
...
Type type = Type.GetType("SomeNamespace." + whichClass);
TestAbstract test = (TestAbstract) Activator.CreateInstance(type);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With