Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 系统、动作和非静态变量_C#_Events_Delegates - Fatal编程技术网

C# 系统、动作和非静态变量

C# 系统、动作和非静态变量,c#,events,delegates,C#,Events,Delegates,这可能是重复的,但我找不到任何解释这种行为的线索。至少不属于操作(基本上是没有返回类型的Func)。这与静态引用有关 看看这两个例子。我只是想订阅System.Action OnButton1Down,以便在使用.Invoke()调用操作时使其调用非静态函数 为什么第一种方法有效,而第二种或第三种方法无效?我更愿意保存/准备操作,这样我也可以通过简单地执行:OnButton1Down-= System.Action OnButton1Down; void MyNonStaticFunction

这可能是重复的,但我找不到任何解释这种行为的线索。至少不属于
操作
(基本上是没有返回类型的Func)。这与静态引用有关

看看这两个例子。我只是想订阅
System.Action OnButton1Down
,以便在使用
.Invoke()
调用
操作时使其调用非静态函数

为什么第一种方法有效,而第二种或第三种方法无效?我更愿意保存/准备
操作,这样我也可以通过简单地执行:OnButton1Down-=

System.Action OnButton1Down;

void MyNonStaticFunction() { }

// This example works
void MyFirstFunction()
{
    OnButton1Down += () => { MyNonStaticFunction(); };
}


// This example gives the following error on "MyNonStaticFunction()":
// "A field initializer cannot reference the non-static field, method
// or property MyNonStaticFunction()."
System.Action MyAction = () => { MyNonStaticFunction(); };

void MySecondStartFunction()
{
    OnButton1Down += MyAction;
}

// This example is to show what happens, if I just try to subscribe the raw
// method to the Action, as suggested in the comments.
// It gives the following error on "MyNonStaticFunction()":
// "Cannot implicitly convert type 'void' to type 'System.Action'."
void MyThirdStartFunction()
{
    OnButton1Down += MyNonStaticFunction();
}

我有点理解这些错误是有意义的,但我不明白为什么第一个例子是正确的。我更希望能够执行其他任何一个示例。

编译器不允许您在对象完全构造之前访问任何实例成员(即,所有字段初始值设定项都已运行)

要解决这个问题,您可以在类构造函数中初始化
MyAction
,它将在所有字段初始值设定项之后运行

编辑:回答问题的第二部分:

OnButton1Down += MyNonStaticFunction();

您正在调用
MyNonStaticFunction
,而不是将其转换为委托!删除
()
,它会工作得更好

请将代码作为文本而不是图像发布。它允许我们将其复制/粘贴到Visual Studio中,并尝试重现问题并尝试解决方案?如何处理/键入
OnButton1Down
delcareed/typed?我很确定他们计划在这里提到的C#8中允许这样做:。。。Fyiaded更多解释,文本代码等更新我的答案,以解决您的第二个问题!非常感谢。这是丢失的那块。我可以简单地将我的非静态方法分配给构造函数中的临时操作变量。完美的