将对象实例数据传递给属性

发布于 2024-08-15 20:43:58 字数 360 浏览 12 评论 0原文

我想将某些数据从对象的实例传递到其属性,但我很难理解如何实现它。下面是一个示例:

[AuthenticateAttribute]
public class MyController: Controller
{
    UserInfo info;
}

其想法是 AuthenticateAttribute 实例将填充 UserInfo 实例。

我想将对 info 的引用传递给 AuthenticateAttribute 实例,从而消除属性与特定 MyController 类之间的强耦合。

这可能吗?

I would like to pass certain data from an instance of an object to its attribute, and I have troubles inderstanding how to implement it. Here's a sample:

[AuthenticateAttribute]
public class MyController: Controller
{
    UserInfo info;
}

The idea is that AuthenticateAttribute instance would populate the UserInfo instance.

I want to pass reference to info to an instance of AuthenticateAttribute and thereby eliminate strong coupling between the attribute and the particular MyController class.

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

拔了角的鹿 2024-08-22 20:43:58

IMO 属性本身不应具有 UserInfo 字段。请记住,它所应用的类型将有一个该属性的实例,而不是该类型的每个实例都有一个。

如果您可以给出更完整的示例(显示它所应用的代码),我们也许能够帮助更多...

The attribute itself shouldn't have the UserInfo field IMO. Bear in mind that there will be one instance of the attribute for the type it's applied to - not one per instance of that type.

If you could give a fuller example (showing the code it's applied to) we may be able to help more...

浪漫之都 2024-08-22 20:43:58

控制器的 ViewData 集合可通过属性访问,您可以将 UserInfo 对象添加到其中,然后在控制器的操作中访问它。
您还可以使用包含 UserInfo 的类型化模型。此处描述了此场景 从授权属性获取权限?

更改属性中的类型字段应用于此并不常见,您必须非常谨慎。

The ViewData collection of the controller is accessible from the attribute and you can add your UserInfo object to it and then access it in the controller's acions.
You can also use the a typed model containing UserInfo. This scenario is described here Get permission from Authorize Attribute?

Changing type fields in attribute that is applied to it is not common and you have to be very cautious.

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