|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Question about MemberInfo.ReflectedTypecalled it (so it can say, "ClassX called me"). Without having to pass the type down the chain. To do this, MethodA walks back up the StackTrace and use GetMethod() looking for the first method it finds with a custom attribute I created. The problem I'm having is with derived classes which don't override a method that calls MethodA. It turns out (in this case) that both DeclaringType and ReflectedType return the base type rather than the derived type. I boiled this down to: namespace Template { public class ClassA { public virtual string Declaring { get { return ( (new System.Diagnostics.StackTrace ( 0 , false )).GetFrames() [ 0 ].GetMethod().DeclaringType.Name ) ; } } public virtual string Reflected { get { return ( (new System.Diagnostics.StackTrace ( 0 , false )).GetFrames() [ 0 ].GetMethod().ReflectedType.Name ) ; } } } public class ClassB : ClassA { } public class Template { [System.STAThread] public static void Main ( string[] args ) { ClassA a = new ClassA() ; ClassB b = new ClassB() ; System.Console.WriteLine ( a.Declaring ) ; System.Console.WriteLine ( a.Reflected ) ; System.Console.WriteLine ( b.Declaring ) ; System.Console.WriteLine ( b.Reflected ) ; // Shouldn't this report ClassB? return ; } } } The result is: ClassA ClassA ClassA ClassA I can certainly understand why DeclaringType return the base type, but I had hoped that ReflectedType would return the actual type that called it, and that the result would be: ClassA ClassA ClassA ClassB <- note How can I do this? Am I doing something wrong? Is there a better way? Is ReflectedType broken? PIEBALD wrote:
> How can I do this? I can't think of a way to do this, right now - but no, it doesn't look> Am I doing something wrong? > Is there a better way? > Is ReflectedType broken? like you're doing anything wrong, and no, I don't think ReflectedType is broken. It looks like the StackTrace sees a method of ClassA on the stack, and so uses typeof(ClassA) to get the MethodInfo. (You'd think that (with instance methods) it could examine the `this` parameter, but perhaps it can't do this in every case because of optimization, while the instruction pointer is an unequivocable cue to which method is running.)
Other interesting topics
|
|||||||||||||||||||||||