使用“new SomeObject”在自定义属性中
我在游戏中使用自定义属性来定义聚合组件之间的依赖关系。
[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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能。
属性被编译为程序集中的元数据。
属性参数只能是基元或
Type
对象。You can't.
Attributes are compiled to metadata in the assembly.
Attribute parameters can only be primitives or
Type
objects.正如 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.
您无法更改属性的参数,因为它们是编译并存储在程序集元数据中的。
您可以在组件上实现一个接口,例如 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.