c# - 选择重载方法作为参数

标签 c#

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/

相关文章:

c# - 在 .NET MVC 4 (Web API) 中,如何拦截对 Controller 的请求并更改其内容类型?

c# - 本地化 WPF 应用程序不起作用?

c# - Google Oauth 2.0 redirect_uri_mismatch - 端口在回调时更改

c# - 如何在 Windows 中嵌入 tabtip.exe

c# - 将字符串写入 UTF-8 文件(无 BOM)时的奇怪行为 - 返回 ANSI 文件

c# - Web 服务调用后响应对象中的属性为空

c# - Autofac 启用类拦截器

c# - 如何使用 C# 读取 Microsoft Edge 历史记录

c# - 使用 OR 的 LINQ WHERE

c# - 如何在 ASP.NET Core 中使用模型验证来验证所需的查询字符串字段