이것은 중복되었을 수 있지만이 동작을 설명하는 스레드를 찾을 수 없습니다. 최소한 Action
(기본적으로 반환 유형이없는 Func)과 관련이 없습니다. 정적 참조와 관련이 있습니다.System.Action 및 비 정적 변수
이 두 가지 사례를 살펴보십시오. 그냥 System.Action OnButton1Down
에 가입하려고 시도하는 것입니다. Action
이 .Invoke()
으로 호출 될 때 비 정적 함수를 호출하도록합니다.
첫 번째 방법은 효과가 있지만 두 번째 또는 세 번째 방법은 효과가없는 이유는 무엇입니까? 나는 차라리 Action
저장/준비 할 것이다, 그래서 나는 단순히 수행하여, 속임수없이 다시 취소 할 수 있습니다 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();
}
나는 종류의 오류가 의미를 이해하지만 그렇게하지 왜 첫 번째 예제가 OK인지 확인하십시오. 나는 오히려 다른 예제들 중 하나를 할 수있을 것입니다.
코드를 이미지가 아닌 텍스트로 게시하십시오. 이를 통해 Visual Studio에 복사/붙여 넣기를하고 문제를 재현하고 솔루션을 시도 할 수 있습니다. –
왜 단순히'_playerInput.OnButton1Down + = MyNonStaticFunction; '을 쓰지 않는거야? 'OnButton1Down'은 어떻게 delcared/typed됩니까? –
메신저 꽤 그들은 여기에 언급 된 C# 8에서 이것을 허용 할 계획 : https : //www.kenneth-truyers.net/2016/01/20/new-features-in-c-sharp-7/ ... FYI – thanatorr