如何动态调用方法的类名?

编程入门 行业动态 更新时间:2024-10-27 14:30:48
本文介绍了如何动态调用方法的类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以将输入变量用作方法的类名?

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 :)

更多推荐

如何动态调用方法的类名?

本文发布于:2023-11-11 23:54:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579901.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!