C#是否存在指定重载方法作为委托或方法参数的语法?
C# 指定选取重载方法作为委托或参数的通用方式
问题背景
以下C#代码中,重载的Show方法无法直接赋值给Formatter委托或传入Format方法,会触发编译错误:
namespace PickOverload; class Program { delegate string Formatter( object o ); string Show( double a ) { return a.ToString(); } string Show( int a ) { return a.ToString(); } string Format( Formatter f, object o ) { return f( o ); } void SelectArgument() { // 错误 CS1503: 无法将方法组转换为Formatter Format( Show, 1.234 ); } void SelectDelegate() { // 错误 CS0123: 没有匹配Formatter的Show重载 Formatter x = this.Show; } void Run() { SelectArgument(); SelectDelegate(); } static void Main( string[] args ) { new Program().Run(); } }
核心需求:不修改现有方法/委托定义的前提下,用通用语法指定选取某一Show重载,作为委托实例或方法参数。
通用解决方案
1. Lambda表达式显式指定重载
通过Lambda将委托参数强制转换为目标重载的参数类型,明确告诉编译器要调用的重载版本:
// 选取Show(double)重载赋值给Formatter Formatter doubleFormatter = o => Show((double)o); // 选取Show(double)作为Format方法参数 Format(o => Show((double)o), 1.234); // 若要选取Show(int)重载,只需转换为int类型 Formatter intFormatter = o => Show((int)o); Format(o => Show((int)o), 123);
2. 显式转换为匹配重载的委托类型
先将方法组转换为与目标重载签名完全一致的委托(比如Func<T, TResult>),再适配到目标委托:
// 绑定Show(double)到匹配的Func委托 Func<double, string> doubleShow = Show; // 适配为Formatter Formatter x = o => doubleShow((double)o); // 直接作为参数传递时可嵌套转换 Format(o => ((Func<double, string>)Show)((double)o), 1.234);
3. 定义专用委托绑定重载
如果需要重复使用某一重载,可先定义与该重载签名完全匹配的委托类型,直接绑定方法组:
// 定义与Show(double)签名一致的委托 delegate string DoubleShowHandler(double a); // 直接绑定到Show(double)重载 DoubleShowHandler doubleShow = Show; // 适配为Formatter Formatter x = o => doubleShow((double)o);
这些方法的本质都是提供明确的类型信息,消除编译器对重载方法的选择歧义。
内容的提问来源于stack exchange,提问作者cskwg
相关产品推荐
相关产品推荐

