将匿名类型附加到对象;如何找回它?
我正在使用 .NET BackgroundWorker
类。作为其功能的一部分,您可以调用名为 ReportProgress
的方法,该方法允许您传入后台任务已完成的百分比以及可选的用户参数。
最终,ReportProgress 调用事件处理程序,并且可选的用户参数成为事件参数的“UserState”成员。
这是一个快速示例,以防我不清楚:
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(...)
}
我的问题是,如何访问匿名类型中的“标题”值?我想我需要使用反射,但到目前为止我运气不佳。
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 sample 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 C# 4.0:
您可以使用反射,但它会很大、很慢而且很丑。命名类型会更明智。
If you are using C# 4.0:
You can use reflection, but it would be big, slow and ugly. A named type would be more sensible.
不要使用匿名对象。它们的范围仅限于当前方法。一旦离开定义它们的当前方法的范围,访问它们就变成了 PITA。因此,定义一个简单的类,然后转换为该类:
然后:
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:
and then:
您不能也没有理由不创建一个类来传递值。
可能性是转换为
动态
,然后获取属性,但我不推荐它。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.