How do I find the type of the object instance of the caller of the current function?

前端 未结 5 585
误落风尘
误落风尘 2021-02-06 07:37

Currently I have the function CreateLog() for creating a a log4net Log with name after the constructing instance\'s class. Typically used as in:

class MessageRe         


        
5条回答
  •  孤街浪徒
    2021-02-06 08:05

    Walk up the stack checking for base class - derived class relationship.

            var type = new StackFrame(1).GetMethod().DeclaringType;
            foreach (var frame in new StackTrace(2).GetFrames())
                if (type != frame.GetMethod().DeclaringType.BaseType)
                    break;
                else
                    type = frame.GetMethod().DeclaringType;
            return CreateLogWithName(type.FullName);
    

    You may want to put in a check that the methods examined are constructors. But a scenario where the subclass is instantiating the superclass in a method other than it's constructor, may still want the current behaviour.

提交回复
热议问题