Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use less code for this situation [closed]

Tags:

c#

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?

like image 214
Lang thang Avatar asked Nov 30 '25 11:11

Lang thang


1 Answers

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);
like image 168
Jon Skeet Avatar answered Dec 03 '25 02:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!