C#中无法对UILibs类型使用[]索引访问成员函数问题
解决C#类无法使用[]索引访问方法的问题
错误原因
C#自定义类默认不支持[]索引操作,你需要为UILibs类实现自定义索引器,或者通过反射动态获取方法。
方案1:实现自定义索引器(推荐,性能更高)
适合方法数量固定的场景,直接在类中添加索引器并手动映射方法名称:
using System; namespace UIC { class UILibs { // 原有方法 public string UI_DarkRound_MML() { return @" local firstUIMML = 'Hello, first UI test' print(firstUIMML) "; } // 自定义索引器 public Func<string> this[string methodName] { get { return methodName switch { "UI_DarkRound_MML" => UI_DarkRound_MML, // 新增方法时在此处添加对应case _ => throw new KeyNotFoundException($"方法 {methodName} 不存在") }; } } } }
调用示例:
UILibs mlib = new UILibs(); var selected = "DarkRound"; private void createUILibraryButton_Click(object sender, EventArgs e) { var func = mlib["UI_" + selected + "_MML"]; string result = func(); // 执行方法获取返回值 }
方案2:使用反射(灵活,适合动态场景)
如果类会频繁新增方法,不想手动维护索引映射,可以用反射动态获取方法:
using System; using System.Reflection; namespace UIC { class UILibs { public string UI_DarkRound_MML() { return @" local firstUIMML = 'Hello, first UI test' print(firstUIMML) "; } // 封装反射逻辑为索引器 public Func<string> this[string methodName] { get { MethodInfo method = GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance); if (method == null) throw new KeyNotFoundException($"方法 {methodName} 不存在"); // 将方法转换为委托 return (Func<string>)Delegate.CreateDelegate(typeof(Func<string>), this, method); } } } }
调用方式和方案1完全一致,无需手动维护方法映射,但反射性能略低于直接索引器。
内容的提问来源于stack exchange,提问作者RealLinen
相关产品推荐
相关产品推荐

