Why does the C# compiler not fault code where a static method calls an instance method?

前端 未结 3 2100
半阙折子戏
半阙折子戏 2021-01-30 00:08

The following code has a static method, Foo(), calling an instance method, Bar():

public sealed class Example
{
    int count;

    pub         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-30 00:25

    Foo has a parameter "x" that is dynamic, which means Bar(x) is a dynamic expression.

    It would be perfectly possible for Example to have methods like:

    static Bar(SomeType obj)
    

    In which case the correct method would be resolved, so the statement Bar(x) is perfectly valid. The fact that there is an instance method Bar(x) is irrelevent and not even considered: by definition, since Bar(x) is a dynamic expression, we have deferred resolution to runtime.

提交回复
热议问题