问题描述:

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))]

网友答案:

You can't.

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

网友答案:

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.

网友答案:

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.

相关阅读:
Top