问题
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