简体   繁体   English

多态代表

[英]Polymorphic delegates

C# chokes on C#窒息

delegate void Bar<T>(T t);

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

The workaround is to use an interface 解决方法是使用界面

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

but now I need to go out of my way to define the implementations of the interface. 但现在我需要尽力定义接口的实现。 Can I achieve the same thing with delegates and simple methods? 我可以使用委托和简单方法实现相同的目的吗?

This is not possible because you cannot assign an open generic method to a delegate. 这是不可能的,因为您不能将开放的通用方法分配给委托。 It would be an interesting new feature to suggest, but currently C# does not allow it. 建议使用这将是一个有趣的新功能,但目前C#不允许使用。

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 interface workaround you already mentioned: 您已经提到的接口解决方法:

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());

Maybe your example does not quite illustrate your intention but what is the point of generics here? 也许您的示例不能完全说明您的意图,但是泛型在这里的意义是什么? You are not using the the type T in any useful manner and I would be using object instead of T . 您没有以任何有用的方式使用类型T,而我将使用object而不是T

I can see some usefulness to having eg a "SerializeSomething(thing as T)" routine which would have a type it could pass along to other generics. 我可以看到使用“ SerializeSomething(thing as T)”例程很有用,该例程的类型可以传递给其他泛型。 Unfortunately, I think such a delegate would have to have some extra type information associated with it to make such generics work. 不幸的是,我认为这样的委托必须具有一些与之相关的额外类型信息,才能使此类泛型工作。 For example, the type T may not be the actual type of "thing". 例如,类型T可能不是“事物”的实际类型。 If "thing" is declared as SomeBaseType but is actually a DerivativeOfSomeBaseType, the code SerializeSomething(thing) will call SerializeSomething(thing). 如果将“事物”声明为SomeBaseType,但实际上是DerivativeOfSomeBaseType,则代码SerializeSomething(thing)将调用SerializeSomething(thing)。 I know of nothing means in the delegate mechanism by which type SomeBaseType would get passed to the target of a delegate. 我不知道在委托机制中,将SomeBaseType类型传递给委托目标的任何方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM