How to call Method's Class Name dynamically?

南楼画角 提交于 2021-02-10 14:13:10

问题


Is it possible to use an input variable as a Method's Class Name?


What I'm using now:

Switch/Case with multiple Namespace.Class.Method()'s.

Each Codec Method is in its own Class.

public static void SetControls(string codec_SelectedItem)
{
    switch (codec_SelectedItem)
    {
        case "Vorbis":
            Codec.Vorbis.Set();
            break;

        case "Opus":
            Codec.Opus.Set();
            break;

        case "AAC":
            Codec.AAC.Set();
            break;

        case "FLAC":
            Codec.FLAC.Set();
            break;

        case "PCM":
            Codec.PCM.Set();
            break;
    }
}

Trying to simplify:

A single Method with a dynamic Class.
Use SelectedItem as Method's Class Name.

public static void SetControls(string codec_SelectedItem)
{
    Codec.[codec_SelectedItem].Set(); 
}

回答1:


Just make a dictionary with instances of the differenct codecs, initialize the dictionary a single time with all codecs. And then get any codec by name whenever you need it. Each codec must be a separate non-static class implementing a ICodec interface you create.

Example, unvalidated c#, to give you the gist:

private static Dictionary<string, ICodec> _codec;

public static void Initialize()
{
    _codec = new Dictionary<string, ICodec> { 
        { "Vorbis", new VorbisCodec() }
        { "Opus", new OpusCodec() }
    };
}

public static void SetControls(string codecName)
{
    _codec[codecName].set();
}

public interface ICodec
{
    void set();
}

Addition as you commented to have it even more compact:

You can also use reflection to get a class by name, instantiate it and then call the .set() method:

((ICodec) Activator.CreateInstance(Assembly.GetExecutingAssembly().GetType(codecClassNameHere))).set();

I advise against it though. Code should also be readable. The Dictionary approach shows very cleanly what's going on. Reflection hides that, this is often more annoying for maintaining the code later on, than the "coolness" of making it very compact with reflection now :)



来源:https://stackoverflow.com/questions/65182202/how-to-call-methods-class-name-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!