【发布时间】: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参数提供参数。如果直接调用它不起作用,您希望它在间接调用时如何起作用?