将匿名类型附加到对象;如何找回它?

发布于 2024-11-06 09:31:59 字数 565 浏览 1 评论 0原文

我正在使用 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

留蓝 2024-11-13 09:31:59

如果您使用 C# 4.0:

dynamic o = e.UserState;
o.title;

可以使用反射,但它会很大、很慢而且很丑。命名类型会更明智。

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.

街道布景 2024-11-13 09:31:59

不要使用匿名对象。它们的范围仅限于当前方法。一旦离开定义它们的当前方法的范围,访问它们就变成了 PITA。因此,定义一个简单的类,然后转换为该类:

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

然后:

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

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;
}
油饼 2024-11-13 09:31:59

您不能也没有理由不创建一个类来传递值。

可能性是转换为动态,然后获取属性,但我不推荐它

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文