PrettyPrincessKitty FS
PrettyPrincessKitty FS

Reputation: 6400

Using 'new SomeObject' in custom attributes

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

Upvotes: 0

Views: 85

Answers (3)

Robert Levy
Robert Levy

Reputation: 29083

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.

Upvotes: 1

Optillect Team
Optillect Team

Reputation: 1747

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.

Upvotes: 0

SLaks
SLaks

Reputation: 888087

You can't.

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

Upvotes: 2

Related Questions