[英]Reducing number of locally defined fields
I have a class that has a number of methods that follow the below pattern: 我有一个具有许多遵循以下模式的方法的类:
public void GetSomeData1(DataParameters[] parameters, Action responseHandler)
{
_getSomeData1ResponseHandler = responseHandler;
Transactions.GetSomeData1(SomeData1ResponseHandler, parameters);
}
private void SomeData1ResponseHandler(Response response)
{
if (response != null)
{
CreateSomeData1(response.Data);
}
}
public void CreateSomeData1(Data data)
{
//Create the objects and then invoke the Action
...
if(_getSomeData1ResponseHandler != null)
{
_getSomeData1ResponseHandler();
}
}
So, some external class calls GetSomeData1 and passes in an Action, which should be called when the data is available. 因此,一些外部类调用GetSomeData1并传递一个Action,当数据可用时应调用该Action。 GetSomeData1 stores the response Action and calls Transactions.GetSomeData1 (an async call). GetSomeData1存储响应Action并调用Transaction.GetSomeData1(异步调用)。 Once that async call is finished, the data is created and the original passed in Action is called. 异步调用完成后,将创建数据并调用在Action中传递的原始数据。
The thing is, for every different GetSomeData call I have, I need to store the passed in Action so I can reference it later. 事实是,对于我拥有的每个不同的GetSomeData调用,我都需要存储传递的Action,以便以后引用。 Is there a way I can somehow pass the original Action to the final method (CreateSomeData1) without storing it? 有没有一种方法可以以某种方式将原始Action传递给最终方法(CreateSomeData1),而不存储它?
Thanks. 谢谢。
You can pass the data along as a captured variable with lambda expressions. 您可以使用lambda表达式将数据作为捕获的变量传递。 No need for class fields. 不需要类字段。
public void GetSomeData1(DataParameters[] parameters, Action responseHandler)
{
Transactions.GetSomeData1(response => SomeData1ResponseHandler(response, responseHandler), parameters);
}
private void SomeData1ResponseHandler(Response response, Action responseHandler)
{
if (response != null)
{
CreateSomeData1(response.Data, responseHandler);
}
}
public void CreateSomeData1(Data data, Action responseHandler)
{
//Create the objects and then invoke the Action
...
if(responseHandler != null)
{
responseHandler();
}
}
Internally, the compiler will create classes and fields to hold the data, but the code you write is cleaner and easier to maintain. 在内部,编译器将创建类和字段来保存数据,但是您编写的代码更干净,更易于维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.