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() {
// error CS1503: Argument 1: cannot convert from 'method group' to 'Program.Formatter'
Format( Show, 1.234 );
}
void SelectDelegate() {
// error CS0123: No overload for 'Show' matches delegate 'Program.Formatter
Formatter x = this.Show;
}
void Run() {
SelectArgument();
SelectDelegate();
}
static void Main( string[] args ) {
new Program().Run();
}
}
是否有 C# 语法来选择重载的 Show
方法之一作为 Format
方法或委托(delegate)的参数?
我不是在寻找上述示例的解决方案,而是在寻找为委托(delegate)或方法参数选择多个重载方法之一的方法。
同样的问题:
void Run() {
double f = 1.234;
Format( Show, f );
Formatter x = this.Show;
}
static void Main(string[] args ) {
new Program().Run();
}
最佳答案
您可以使用泛型来做到这一点,例如:
internal delegate string Formatter<T>(T o);
internal static string Show(double a) => a.ToString();
internal static string Show(int a) => a.ToString();
internal static string Format<T>(Formatter<T> f, T o) => f(o);
static void Main(string[] args)
{
double f = 1.234;
Format(Show, f);
}
关于c# - 选择重载方法作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74546165/