I have a class which I am using as a descriptor for an object. In that descriptor, there are several Type
references for classes that are to be instantiated for different operations involving that object. I was thinking of pulling those references out and replacing them with attributes on the descriptor class.
From this:
class MyDescriptor : BaseDescriptor {
public Type Op1Type { get; }
public Type Op2Type { get开发者_JAVA百科; }
}
To this:
[Op1(typeof(foo))]
[Op2(typeof(bar))]
class MyDescriptor : BaseDescriptor {
}
I use attributes very rarely. Would this be considered a bad use of them?
I think this is a good use of attributes, especially if you want to be able to instance the decorating classes through reflection prior to instancing the class they decorate. There are many benefits to using attributes, and this is just one.
Regardless of your intent, I don't see a problem with the implementation.
I would personally use Dependency Injection instead of baking the dependency into the Type itself at compile time.
I cannot see any benefit you can get from doing this over instantiating the dependencies by the class in its constructor or initialise.
Dependency Injection allow you to change such behaviour at runtime in addition to the ability to replace them with dummy stubs/mocks.
I don't see any problems in the way you used attributes, but I also don't see any benefits you gained. Maybe if you share more information it would be easier to come up with a solution.
I use such way when want to specify what type of, for example, hash algorithm provider to use.
Child class has the attribute which will be read by parent class and it will create an instance of that type.
Attributes are a fairly elegant way of expressing this in source code, but miserable runtime performance.
You'll want to build a cache at runtime to make lookups fast, perhaps using Dictionary<Type, Type>
.
精彩评论