Let's say we have a situation where we have two classes, ClassA
and ClassB
, and these both have the method DoSomething()
. ClassB
contains a ClassA
as a field, and when ClassB.DoSomething()
is called it delegates the call to ClassA.DoSomething()
. Also, ClassA.DoSomething()
has some attribute on it. So we have something like
class ClassA {
[SomeAttribute]
int DoSomething() { return 0; }
}
class ClassB {
public ClassA CA { get; }
int DoSomething() { return CA.DoSomething(); }
}
My question is, is there some way of applying the attributes that exist on ClassA.DoSomething()
to ClassB.DoSomething()
without repeating that code? What if ClassA.DoSomething()
has multiple attributes? Is开发者_StackOverflow社区 there some attribute that might look like [ApplyAttributes(typeof(ClassA), "DoSomething")]
?
I'm not looking at applying attributes dynamically at runtime, this could all happen at compile time.
This is for a Silverlight solution, so certain reflection techniques such as TypeDescriptors are unavailable to me.
I would create a custom TypeDescriptor that would be responsible for analyzing your ApplyAttributes attribute and returning relevant attributes at run-time.
I think it would be easier to do than some nasty build step that will modify your source-code before compilation.
Attributes are a run time thing. That is knowing what attributes are applied to a class requires a live instance of a class.
Now if/when Microsoft provides the "Compiler as a Service" capability then you may be able to get this information at "compile" time and do something with it. Essentially, unless you parse your code file and modify the C# code of the other classes there is no way to do what you're looking to do at compile time.
If your classes are related by inheritance, then you can define your attributes to be inheritable.
精彩评论