开发者

Store in variable instead of write to console?

See GitHub

static void Main(string[] args)
{
    // do something...

    service.Feedback += new FeedbackService.OnFeedback(service_Feedback开发者_开发知识库);
}

static void service_Feedback(object sender, Feedback feedback)
{
    Console.WriteLine(string.Format("Feedback - Timestamp: {0} - DeviceId: {1}", feedback.Timestamp, feedback.DeviceToken));
}

Instead of output for display in the console how do you store it into a variable so it can be in the main program?


Well, you'd need to declare the variable:

static Feedback lastFeedback;

and then simply assign it in the method:

static void service_Feedback(object sender, Feedback feedback)
{
    lastFeedback = feedback;
}

You might want to consider making this a List<Feedback> instead of only storing the last feedback received.

Note that if there are multiple threads involved, you'll need to take extra care - particularly if you're using a collection. (List<T> isn't thread-safe.)

Of course you don't have to use a method for the event handler:

service.Feedback += (sender, feedback) => lastFeedback = feedback;

It depends on how comfortable you are with lambda expressions. Even if you don't want to do it inline like that, you could still make your existing handler subscription slightly simpler using a method group conversion:

service.Feedback += service_Feedback;


Using lambda:

class Program
{
    static string feedback; // string to store formatted string, use type Feedback to store the variable itself

    static void Main(string[] args)
    {
        service.Feedback += (s,f) => feedback = String.Format("Feedback - Timestamp: {0} - DeviceId: {1}", f.Timestamp, f.DeviceToken);
    }
}

or classic:

static void service_Feedback(object sender, Feedback f)
{
   feedback = string.Format("Feedback - Timestamp: {0} - DeviceId: {1}", f.Timestamp, f.DeviceToken);
}

This will store just the last feedback.


static void Main(string[] args)
{
    // do something...

    service.Feedback += new FeedbackService.OnFeedback(service_Feedback);
}

static StringBuilder sb = new StringBuilder();
static void service_Feedback(object sender, Feedback feedback)
{
    sb.AppendLine(string.Format("Feedback - Timestamp: {0} - DeviceId: {1}", feedback.Timestamp, feedback.DeviceToken));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜