Determine Calling Object Type in C#

前端 未结 11 876
灰色年华
灰色年华 2021-02-05 14:37

Regardless of whether or not this is a good idea, is it possible to implement an interface where the executing function is aware of the calling object\'s type?

c         


        
11条回答
  •  长情又很酷
    2021-02-05 14:41

    As an alternative approach, have you ever considered offering up a different class based on the type of the object that is asking for the class. Say the following

    public interface IC {
      int DoSomething();
    }
    
    public static CFactory { 
      public IC GetC(Type requestingType) { 
        if ( requestingType == typeof(BadType1) ) { 
          return new CForBadType1();
        } else if ( requestingType == typeof(OtherType) { 
          return new CForOtherType();
        }  
        ...
      }
    }
    

    This would be a much cleaner approach than have each method change it's behavior based on the calling object. It would cleanly separate out the concerns to the different implementations of IC. Additionally, they could all proxy back to the real C implementation.

    EDIT Examining the callstack

    As several other people pointed out you can examine the callstack to determine what object is immediately calling the function. However this is not a foolproof way to determine if one of the objects you want to special case is calling you. For instance I could do the following to call you from SomeBadObject but make it very difficult for you to determine that I did so.

    public class SomeBadObject {
      public void CallCIndirectly(C obj) { 
        var ret = Helper.CallDoSomething(c);
      }
    }
    
    public static class Helper {
      public int CallDoSomething(C obj) {
        return obj.DoSomething();
      }
    }
    

    You could of course walk further back on the call stack. But that's even more fragile because it may be a completely legal path for SomeBadObject to be on the stack when a different object calls DoSomething().

提交回复
热议问题