如何将操作转换为相同签名的已定义委托?

Rya*_*hel 6 c# generics delegates

class Test
{
    public delegate void FruitDelegate(Fruit f);

    public void Notify<T>(Action<T> del) where T : Fruit
    {
        FruitDelegate f = del; // Cannot implicitly convert type 'Action<T>' to 'FruitDelegate
    }
}
Run Code Online (Sandbox Code Playgroud)

水果是一个空洞的课程.这两个代表都有相同的签名.

我似乎无法得到任何这个工作.如果我解释了我想要做的事情(提供一些背景信息),也许会有所帮助.

我想创建一个具有通用静态方法的类,该方法提供类型和方法回调(如上例所示).

我遇到的问题是委托包含一个参数,我不想在方法回调中强制转换它.例如,我想要这个:

public void SomeMethod()
{
    Test.Notify<Apple>(AppleHandler);
}

private void AppleHandler(Apple apple)
{

}
Run Code Online (Sandbox Code Playgroud)

而不是这个:

public void SomeMethod()
{
    Test.Notify<Apple>(AppleHandler);
}

private void AppleHandler(Fruit fruit)
{
    Apple apple = (Apple)fruit;
}
Run Code Online (Sandbox Code Playgroud)

这种事可能吗?一直在努力工作几个小时没有太多运气= /

ojl*_*ecd 7

这是你想要的吗?

static void Main(string[] args)
{

    Program p = new Program();
    p.SomeMethod();
}

public class Fruit
{ }

public class Apple : Fruit { }

public delegate void FruitDelegate<in T>(T f) where T : Fruit;

class Test
{
    public static void Notify<T>(FruitDelegate<T> del)
        where T : Fruit, new()
    {
        T t = new T();
        del.DynamicInvoke(t);
    }
}

private void AppleHandler(Apple apple)
{
    Console.WriteLine(apple.GetType().FullName);
}

public void SomeMethod()
{
    FruitDelegate<Apple> del = new FruitDelegate<Apple>(AppleHandler);
    Test.Notify<Apple>(del);
}
Run Code Online (Sandbox Code Playgroud)