使用“new SomeObject”在自定义属性中

发布于 2024-11-15 04:10:11 字数 548 浏览 6 评论 0原文

我在游戏中使用自定义属性来定义聚合组件之间的依赖关系。

[ComponentDependency(typeof(SomeDependentComponent))]
class SomeComponent : Component {}

但是,这意味着我必须为要以这种方式添加的每个组件使用默认值。我希望能够执行以下操作:

[ComponentDependency(typeof(SomeDependentComponent), ctrParam1, ctrParam2...)]

并将这些直接输入到 Activator.CreateInstance(Type, object[]),但我收到错误。我认为这与编译时的属性有关。我对他们了解不多。

这可能吗?

编辑:如果我要使用参数,它可能看起来像: [ComponentDependency(typeof(PositionalComponent), new Vector2(300, 300))]

I'm using custom attributes in my game to allow me to define dependencies between aggregated components.

[ComponentDependency(typeof(SomeDependentComponent))]
class SomeComponent : Component {}

However, this means I have to use default values for every component I want to add this way. I would like to be able to do:

[ComponentDependency(typeof(SomeDependentComponent), ctrParam1, ctrParam2...)]

And feed these directly into Activator.CreateInstance(Type, object[]), but I get errors. I think it's to do with attributes being compile time. I don't know much about them.

Is this possible?

EDIT: If I were to use parameters, it may look like:
[ComponentDependency(typeof(PositionalComponent), new Vector2(300, 300))]

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

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

发布评论

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

评论(3

谢绝鈎搭 2024-11-22 04:10:11

你不能。

属性被编译为程序集中的元数据。
属性参数只能是基元或Type对象。

You can't.

Attributes are compiled to metadata in the assembly.
Attribute parameters can only be primitives or Type objects.

心舞飞扬 2024-11-22 04:10:11

正如 SLAks 所说,这是行不通的。您正在尝试构建的称为“依赖注入”,这是一种强大且日益流行的模式。有许多为 .NET 构建的依赖注入框架 - 我建议对它们进行一些研究并选择一个 - 它们具有处理您想要执行的操作的机制(通常是 XML 配置文件)。

As SLaks says, this won't work. What you are trying to build is called "Dependency Injection" which is a powerful and increasingly popular pattern. There are many Dependency Injection frameworks built for .NET - I suggest doing some research on them and choosing one - they have mechanisms (usually XML config files) to handle what you are trying to do.

或十年 2024-11-22 04:10:11

您无法更改属性的参数,因为它们是编译并存储在程序集元数据中的。

您可以在组件上实现一个接口,例如 IDependantComponent,并在创建后调用 SetDependency。

You cannot change parameters of attributes, because they are compiled and stored in the assembly metadata.

You might implement an interface on your components e.g. IDependantComponent and call SetDependencies after it's created.

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