开发者

Attached an anonymous type to an object; how to retrieve it?

开发者 https://www.devze.com 2023-03-05 11:10 出处:网络
I\'m playing with the .NET BackgroundWorker class.As part of its functionality you can call a method named ReportProgress that allows you to pass in the percentage your background task has completed,

I'm playing with the .NET BackgroundWorker class. As part of its functionality you can call a method named ReportProgress that allows you to pass in the percentage your background task has completed, along with an optional user parameter.

Eventually ReportProgress calls an event handler and the optional user parameter becomes the "UserState" member of the event argument.

Here's a quick sam开发者_运维知识库ple in case I'm not being clear:

BackgroundProcess.ReportProgress(100, new{title="complete"});
/*****later on, this method is called******/
private void myEventHandler(object sender, RunWorkerCompletedEventArgs e)
{
   //e.UserState is my anonymous type defined in the call to ReportProgress(...)
}

My question is, how can I access the "title" value in my anonymous type? I assume I'll need to use reflection but so far I'm not having great luck.


If you are using C# 4.0:

dynamic o = e.UserState;
o.title;

You can use reflection, but it would be big, slow and ugly. A named type would be more sensible.


Don't use anonymous objects. They are scoped only to the current method. Once you leave the scope of the current method in which they are defined accessing them becomes a PITA. So define a simple class and then cast to this class:

BackgroundProcess.ReportProgress(100, new MyClass { Title = "complete" });

and then:

private void myEventHandler(object sender, RunWorkerCompletedEventArgs e)
{
   var title = ((MyClass)e.UserState).Title;
}


You cannot and there is no reason why you should not create a class to pass the values.

On possibility is casting to dynamic and then getting the property but I do not recommend it.

0

精彩评论

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

关注公众号