【问题标题】:cannot convert from 'method group' to 'Action' [closed]无法从“方法组”转换为“操作”[关闭]
【发布时间】:2022-01-06 12:50:21
【问题描述】:

我有一个名为 Choice 的自定义类,它有两个属性:string Description;Action A;

在主程序中我定义了一个实例Choice c = new Choice("Desc", foo);

下面我定义一个方法public void foo(AnotherClass AC);

现在我想执行 foo() 方法,我必须调用 c.A();c.A.Invoke();,但编译后两者都在实例行出现错误 Arugument 2: cannot convert from 'method group' to 'Action'Choice c = new Choice("Desc", foo);

如果我定义 foo 没有任何参数,例如 public void foo();,它不会给我带来问题

我该如何解决这个问题?

编辑:这是最少的代码:

class Choice
{
    public string Description { get; set; }
    public Action A { get; set; }
    public Choice()
    {
        Description = "";
        A = delegate { };
    }
    public Choice(string Description, Action A) : this()
    {
        this.Description = Description;
        this.A = A;
    }
}

class AnotherClass
{
    // Details of AnotherClass...
}

public void foo(AnotherClass AC)
{
    // do something with AC...
}

static void Main()
{
        AnotherClass Bar; // I want this as an argument into foo()
        Choice c = new Choice("Desc", foo); // I'm stuck here, how do I call foo() with Bar as an argument without changing A's type ?            
        c.Invoke();
}

【问题讨论】:

  • 请提供minimal reproducible example - 如果您可以显示您的代码而不是描述您的代码,会容易得多。
  • 我已经更新了代码
  • 如果您提供的代码确实编译,您希望foo 方法中的AC 参数的值是多少? (作为旁注,我强烈建议您即使在示例代码中也遵循 .NET 命名约定,以避免非常规名称分散注意力。)
  • AC 值与此问题无关,因为我想要一种使用AnotherClass 参数调用foo() 的方法。正如我所说,在没有参数的情况下定义 foo() 对我有用
  • 我看不出它与问题的关系:您指定了一个带有参数的方法。您正在尝试调用该方法。该参数将有一个值 - 那么您希望它具有什么值?换句话说:您实际上是在尝试调用c.Foo() - 这显然行不通,因为您没有为AC 参数提供参数。如果直接调用它不起作用,您希望它在间接调用时如何起作用?

标签: c# methods delegates


【解决方案1】:

A 是一个Action,这意味着它是一个没有任何参数的函数的委托。 foo 不匹配,因为它需要一个 AnotherClass 参数。

你可以:

  • A 的类型更改为Action<AnotherClass>
  • 使用无参数 lambda 初始化 cChoice c = new Choice("Desc", () => foo(someAnotherClass))

【讨论】:

  • 改变A的类型是我做不到的。我尝试了第二个建议,但它给了我'AnotherClass' is a type, which is not valid in the given context 错误
  • 我通过传递实际参数Bar 而不是类类型AnotherClass 来解决第二个建议:Choice c = new Choice("Desc", () => foo(Bar))
  • @samyung_c:Gabriel 从未建议传递类型本身...() => foo(someAnotherClass) 对我来说似乎很清楚...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2013-10-02
  • 1970-01-01
  • 2010-10-18
  • 2015-04-19
  • 1970-01-01
相关资源
最近更新 更多