开发者

Who called the shared method?

I have a parent class (Foo) with a shared method sharedMethod(). It is MustInherit. Bar and Baz classes inherit from Foo. I will do something like that:

Dim baz as New Baz()
Dim bar as New Bar()

baz.sharedMethod()
bar.sharedMethod()

Within Foo's sharedMethod(), I need to know who called it. I need the class name. So, using the above example, it would be,开发者_运维百科 respectively, Baz or Bar.


That's not possible, you don't have the Me variable to know the type of the class. To avoid creating the illusion that it might be possible, you should write it like this:

 Foo.sharedMethod()


Within your function you could use:

Me.GetType().Name

This is assuming that your method is not declared as

Private/Public/Protected Shared MyMethod()

And that when you say "sharedmethod" you only mean that both classes have access to the method. If you have an actual Shared method, then you would need to use something from Reflection and Diagnostics to grab this information as described here.


Why do you need to know this? It doesn't seem like 'the right way' to go about things. If you need the shared method to do something special with its caller then have a Foo as a parameter to the shared method (at which point it's probably not worth it being shared any more!).


You could give a parameter to the sharedmethod and indicate that way.


You should probably think about overriding the method in child classes instead of using shared methods. In the override make sure to call the base class method. If there is functionality inside of the parent method that needs to know what called it (and cannot be moved to the child classes) then you should consider using generics. Then inside of the child class you would pass the child type into the constructor of foo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜