Determine Calling Object Type in C#

前端 未结 11 1066
灰色年华
灰色年华 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 15:02

    Well you could try grabbing the stack trace and determine the type of the caller from there, which is an overkill in my opinion and would be slow.

    How about an interface, that A,B would implement?

    interface IFoo { 
         int Value { get; } 
    }
    

    And then your DoSomething method would look like this:

       public int DoSomething(int input, IFoo foo)
       {
            return input + foo.Value;
       }
    

提交回复
热议问题