代码之家  ›  专栏  ›  技术社区  ›  TK.

函数重载的C#规则

  •  9
  • TK.  · 技术社区  · 15 年前

    我有以下代码:

    public T genericFunc<T>() where T : Component, new()
    {
        T result = new T();
        overloadedFunction( result );
    }
    
    private overloadedFunction ( Component c ) // catch all function
    
    private overloadedFunction ( DerivedFromComponent dfc) // specific function
    

    当我调用上述代码时:

    genericFunc<DerivedFromComponent>();
    

    2 回复  |  直到 15 年前
        1
  •  15
  •   Jon Skeet    15 年前

    编译器在中执行重载解析 genericFunc . 此时它不知道要提供什么类型的参数,所以它只知道它可以调用第一个重载。

    总是 dynamic ).

    一个不使用泛型的简单示例:

    void Foo(string text) { }
    void Foo(object o) {}
    ...
    object x = "this is a string";
    Foo(x);
    

    会调用第二个重载,因为 类型 x 只是一个物体。

    关于这个的更多信息,请阅读我最近的文章 article on overloading

        2
  •  3
  •   Josh    15 年前

    jonskeet对重载解析是在编译时确定的这一事实是正确的。我想我会补充另一个答案,这不是你问题的重点,但值得注意。

    在C#4中,可以使用dynamic关键字将重载解析推迟到运行时。请考虑以下打印的代码段:

    Base!
    Derived!
    


    class Base {
    }
    
    class Derived : Base {
    }
    
    void DoSomething(Base x) {
        Console.WriteLine("Base!");
    }
    
    void DoSomething(Derived x) {
        Console.WriteLine("Derived!");
    }
    
    void DoSomething<T>() where T: Base, new() {
        dynamic x = new T();
        DoSomething(x);
    }
    
    void Main()
    {
        DoSomething<Base>();
        DoSomething<Derived>();
    }