Determine Calling Object Type in C#

前端 未结 11 864
灰色年华
灰色年华 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:46

    The easiest answer would be to pass in the sender object like any event with the typical sender, eventargs methodology.

    Your calling code would look like this:

    return c.DoSomething(input, this);
    

    Your DoSomething method would simply check the type using the IS operator:

    public static int DoSomething(int input, object source)
    {
        if(source is A)
            return input + 1;
        else if(source is B)
            return input + 2;
        else
            throw new ApplicationException();
    
    }
    

    This seems like something with a little more OOP. You might consider C an abstract class with an method, and having A,B inherit from C and simply call the method. This would allow you to check the type of the base object, which is not obviously spoofed.

    Out of curiosity, what are you trying with this construct?

提交回复
热议问题