多态代表

Bru*_*nez 5 c# generics delegates interface

C#chokes on

delegate void Bar<T>(T t);

void foo(Bar bar)
{
    bar.Invoke("hello");
    bar.Invoke(42);
}
Run Code Online (Sandbox Code Playgroud)

解决方法是使用接口

interface Bar
{
    void Invoke<T>(T t);
}
Run Code Online (Sandbox Code Playgroud)

但现在我需要不遗余力地定义接口的实现.我可以用委托和简单的方法实现同样的目的吗?

Tim*_*mwi 5

这是不可能的,因为您无法为委托分配开放的通用方法.这将是一个有趣的新功能建议,但目前C#不允许它.

可能的解决方法:

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);
Run Code Online (Sandbox Code Playgroud)

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>);
Run Code Online (Sandbox Code Playgroud)

您已经提到的界面解决方法:

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());
Run Code Online (Sandbox Code Playgroud)


Ali*_*tad 0

也许你的例子并不能完全说明你的意图,但是泛型在这里有什么意义呢?您没有以任何有用的方式使用 T 类型,我将使用object而不是T.