Using a generic parameter for overloaded methods

Why does this program output Generic Value, not Hello world!:

using System;

class Example
{
    public static void Print<T>(T value)
    {
        Console.WriteLine("Generic Value");
    }

    public static void Print(string value)
    {
        Console.WriteLine(value);
    }

    public static void GenericFunc<T>(T value)
    {
        Print(value);
    }

    static void Main()
    {
        GenericFunc("Hello world!");
    }
}

How is the parameter of the generalized method passed under the hood of C #?

+4
source share
2 answers

Overload resolution is only performed at compile time.

Since it GenericFunc<T>does not know if T stringor something else at compile time, it can only use Print<T>(T value)"overload".

Using dynamic, you can change this to dynamic dispatch and get the expected behavior:

Print((dynamic)value);

, value.

+13

, ( ). , .

OOP

O OOP Object .

, . String . , Print.

public static void Print<T>(T value)
{
    Console.WriteLine(value.ToString());
}

nullity ref.

    public static void Print<T>(T value) where T : class
    {
        if (value != null)
        {
            Console.WriteLine(value.ToString());
        }
    }

    public static void GenericFunc<T>(T value) where T : class
    {
        Print(value);
    }

, , , (. ).

, . , . -, , . -, , : . ToString.

...

, , - .

( Foo) , Foo. IFooCallable:

public interface IFooCallable
{
    void Foo();
}

...

, , , .

. , node (, AST). , .

:

public class Visitor : IVisitor
{
    public void Visit(Foo foo)
    {
        // do something with foo
    }

    public void Visit(Bar bar)
    {
        // do something with bar
    }
}

Visitable

public class Foo : IVisitable
{
    public void Accept(IVisitor visitor)
    {
        visitor.Visit(this);
    }
}

, ( IVisitor, ).

dynamic. , , . , ;)

    public static void Print(dynamic value)
    {
        Console.WriteLine(value);            
    }

    public static void GenericFunc(dynamic value)
    {
        Print(value);
    }

    static void Main(dynamic[] args)
    {
        GenericFunc((dynamic)"Hello World");
    }
+1

Source: https://habr.com/ru/post/1628306/


All Articles