繁体   English   中英

接口,委托,其他? (C#,统一)

[英]Interface, delegate, other? (C#, Unity)

我有的:

public void New_Click()
{           
    MenuManager.GoToMenu(MenuName.NewDescr);
    StartCoroutine(WaitForClose());          
}

IEnumerator WaitForClose()
{
   yield return new WaitWhile(MenuManager.MenuOpen);
   listMonitor.AddToGrid(Descriptor.List.Last());
   yield return null;
}

我想要的是:

public void New_Click()
{
    MenuManager.GoToMenu(MenuName.NewDescr);
    WaitForClose(listMonitor.AddToGrid(Descriptor.List.Last()));
}

基本上,我想在方法调用周围实现一个包装器,但不必在每次使用该方法时都指定 StartCoroutine() 或写出 WaitForClose() 方法。 我对代表和接口几乎没有经验 - 这些是答案吗? 如果是这样,怎么做?

您可以通过允许传递一个Action委托来概括您展示的WaitForClose()方法。 例如:

public void New_Click()
{           
    MenuManager.GoToMenu(MenuName.NewDescr);
    StartCoroutine(WaitForClose(() => listMonitor.AddToGrid(Descriptor.List.Last())));          
}

IEnumerator WaitForClose(Action action)
{
   yield return new WaitWhile(MenuManager.MenuOpen);
   action();
   yield return null;
}

扩展上述内容,您可以稍微简化调用,使其更接近您的“我想要的”示例:

public void New_Click()
{           
    MenuManager.GoToMenu(MenuName.NewDescr);
    WaitForClose(() => listMonitor.AddToGrid(Descriptor.List.Last()));          
}

void WaitForClose(Action action)
{
    StartCoroutine(WaitForCloseCoroutine(action));
}

IEnumerator WaitForCloseCoroutine(Action action)
{
   yield return new WaitWhile(MenuManager.MenuOpen);
   action();
   yield return null;
}

彼得确切地知道我要去哪里 go。 但是由于您对这个概念完全陌生,并且可能会阅读更多有关它的信息,所以我将从这个开始。

关键字“Action”,而不是 int、string、someClass 等,您告诉该方法您希望在特定时间点到来时调用过程/方法,正如 Peter 通过调用较低的 -案例“动作()”。

您可以做的另一件很酷的事情是甚至允许需要某种附加参数的操作。 也许您希望有条件地允许一些时间延迟,计算值或其他任何东西。 您还可以指定要传入的数据类型参数。 唯一的区别是签名,例如

public void SomeFunction( Action<int> doSomething )
{
    // suppose some randomized value that you want the function to handle
    var someRand = SomeIntValueFromSomeRandomFunction();
    // notice the Action signature is saying it should be a function that 
    // will expect and integer data type to be passed to it when actually called.
    // above I get some random number, then call that Action method with it.
    doSomething( someRand );
}

同样,您可以使用返回值的函数来执行操作。 唯一的区别是最后一个参数是在调用 function 之后返回的预期数据类型。

使用 ACTIONS 也使用 FUNCTIONS

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM