Polymorphic Delegates

C # chokes on

delegate void Bar<T>(T t);

void foo(Bar bar)
{
    bar.Invoke("hello");
    bar.Invoke(42);
}

The workaround is to use the interface

interface Bar
{
    void Invoke<T>(T t);
}

but now I need to go the way to determine the interface implementations. Can I get the same with delegates and simple methods?

+3
source share
3 answers

This is not possible because you cannot assign an open public method to the delegate. It would be an interesting new opportunity to offer, but currently C # does not allow this.

Possible workarounds:

delegate void Bar(object t);

void foo(Bar bar)
{
    bar.Invoke("hello");
    bar.Invoke(42);
}

void BarMethod(object t)
{
    if (t is int)
        // ...
    else if (t is string)
        // ...
}

foo(BarMethod);

delegate void Bar<T>(T t);

void foo(Bar<string> stringBar, Bar<int> intBar)
{
    stringBar.Invoke("hello");
    intBar.Invoke(42);
}

void BarMethod<T>(T t)
{
    // ...
}

foo(BarMethod<string>, BarMethod<int>);

The workaround for the interface that you already talked about:

interface IBar
{
    void Invoke<T>(T t);
}

void foo(IBar bar)
{
    bar.Invoke("hello");
    bar.Invoke(42);
}

class BarType : IBar
{
    public void Invoke<T>(T t)
    {
        // ...
    }
}

foo(new BarType());
+5
source

, , ? T , object T.

0

, , " SerializeSomething ( T)", , . , , , , . , T "". "" ​​ SomeBaseType, DerivativeOfSomeBaseType, SerializeSomething () SerializeSomething (). , SomeBaseType .

0

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


All Articles