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

前端 未结 5 587
误落风尘
误落风尘 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:21

    Is there anyone who can show me how to implement a zero argument CreateLog() that gets the name from the subclass and not the declaring class?

    I don't think you'll be able to do it by looking at the stack frame.

    While your class is IMReceiver, the call to CreateLog method is in the MessageReceiver class. The stack frame must tell you where the method is being called from, or it wouldn't be any use, so it's always going to say MessageReceiver

    If you called CreateLog explicitly in your IMReceiver and other classes, then it works, as the stack frame shows the method being called in the derived class (because it actually is).

    Here's the best thing I can come up with:

    class BaseClass{
      public Log log = Utils.CreateLog();
    }
    class DerivedClass : BaseClass {
      public DerivedClass() {
        log = Utils.CreateLog();
      }
    }
    

    If we trace creation of logs, we get this:

    new BaseClass();
    # Log created for BaseClass
    
    new DerivedClass();
    # Log created for BaseClass
    # Log created for DerivedClass
    

    The second 'log created for derived class' overwrites the instance variable, so your code will behave correctly, you'll just be creating a BaseClass log which immediately gets thrown away. This seems hacky and bad to me, I'd just go with specifying the type parameter in the constructor or using a generic.

    IMHO specifying the type is cleaner than poking around in the stack frame anyway

    If you can get it without looking at the stack frame, your options expand considerably

提交回复
热议问题