无法从 'method group' 转换为 'Action'
cannot convert from 'method group' to 'Action'
我有一个名为 Choice
的自定义 class,它有两个属性: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();
}
A
是一个 Action
,这意味着它是一个没有任何参数的函数的委托。 foo
不匹配,因为它需要一个 AnotherClass
参数。
您可以:
- 将
A
的类型更改为 Action<AnotherClass>
- 使用无参数 lambda 初始化
c
:Choice c = new Choice("Desc", () => foo(someAnotherClass))
我有一个名为 Choice
的自定义 class,它有两个属性: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();
}
A
是一个 Action
,这意味着它是一个没有任何参数的函数的委托。 foo
不匹配,因为它需要一个 AnotherClass
参数。
您可以:
- 将
A
的类型更改为Action<AnotherClass>
- 使用无参数 lambda 初始化
c
:Choice c = new Choice("Desc", () => foo(someAnotherClass))