是否可以将输入变量用作方法的类名?
Is it possible to use an input variable as a Method's Class Name?
我现在正在使用什么:
Switch / Case .
每个编解码器方法都在其自己的类中.
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; } }试图简化:
具有动态 Class 的单个 Method .使用 SelectedItem 作为方法的类名.
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(); } 推荐答案只需使用不同编解码器的实例创建字典,然后使用所有编解码器一次初始化字典.然后在需要时按名称获取任何编解码器.每个编解码器必须是实现您创建的ICodec接口的单独的非静态类.
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.
示例,未经验证的C#,为您提供要点:
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:
您还可以使用反射按名称获取类,实例化它,然后调用.set()方法:
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 :)
更多推荐
如何动态调用方法的类名?
发布评论