【问题标题】:Pick overloaded method as argument选择重载方法作为参数
【发布时间】:2022-11-24 12:35:02
【问题描述】:
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 方法或委托的参数?

我不是在寻找上述示例的解决方案,而是在寻找为委托或方法参数选择多个重载方法之一的方法。

这里有同样的问题:

void Run() { 
  double f = 1.234; 
  Format( Show, f ); 
  Formatter x = this.Show; 
} 

static void Main(string[] args ) { 
  new Program().Run(); 
}

【问题讨论】:

  • 同样的问题:void Run() { double f = 1.234;格式(显示,f);格式化程序 x = this.Show; } static void Main( string[] args ) { new Program().Run(); }
  • 请不要在 cmets 中添加更多信息。改为编辑您的问题。

标签: c#


【解决方案1】:

您可以使用泛型来做到这一点,例如:

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);
}

【讨论】:

  • 实际上,Format 方法要大得多,所以我不想为它使用泛型。关于重载方法的选择,我的问题非常具体。我在 C# 中找不到执行此操作的有效语法。它更像是一个普遍的问题:如何在 C# 中获取指向重载方法的指针。
  • Show 方法都没有采用 object,因此您不能转换为您的 Formatter(object) 委托。泛型是这里唯一好的解决方案。
  • 另外 @cskwg 现在你说它要求不使用泛型,这使它成为一个变色龙问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
相关资源
最近更新 更多