Reputation: 331
I have 2 fields like
private IFruit fruit;
private Banana banana;
An instance of Banana
is created like this:
var banana = new Banana(fruit);
I want to create an attribute for Banana
fields to do the job of creating Banana
instance for me!
Upvotes: 1
Views: 696
Reputation: 26446
Attributes don't cause any code to be executed - you'll have to use reflection to access them. If you want you could implement a base class that has this behavior, and add the reflection code to the constructor:
abstract class AutoCreateBase
{
public MyBase()
{
// Reflection to go through the fields, find the attributes, and use Activator.CreateInstance() on each
}
}
class MyClass : AutoCreateBase
{
[AutoCreate]
private Banana banana;
}
Upvotes: 1