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

前端 未结 3 2079
半阙折子戏
半阙折子戏 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条回答
  •  Happy的楠姐
    2021-01-30 00:36

    The "dynamic" expression will be bound during runtime, so if you define a static method with the correct signature or a instance method the compiler will not check it.

    The "right" method will be determined during runtime. The compiler can not know if there is a valid method there during runtime.

    The "dynamic" keyword is defined for dynamic and script languages, where the Method can be defined at any time, even during runtime. Crazy stuff

    Here a sample which handles ints but no strings, because of the method is on the instance.

    class Program {
        static void Main(string[] args) {
            Example.Foo(1234);
            Example.Foo("1234");
        }
    }
    public class Example {
        int count;
    
        public static void Foo(dynamic x) {
            Bar(x);
        }
    
        public static void Bar(int a) {
            Console.WriteLine(a);
        }
    
        void Bar(dynamic x) {
            count++;
        }
    }
    

    You can add a method to handle all "wrong" calls, which could not be handled

    public class Example {
        int count;
    
        public static void Foo(dynamic x) {
            Bar(x);
        }
    
        public static void Bar(T a) {
            Console.WriteLine("Error handling:" + a);
        }
    
        public static void Bar(int a) {
            Console.WriteLine(a);
        }
    
        void Bar(dynamic x) {
            count++;
        }
    }
    

提交回复
热议问题