如何将一个动作转换成同一个签名的定义的代理? [英] How to convert an action to a defined delegate of the same signature?

查看:121
本文介绍了如何将一个动作转换成同一个签名的定义的代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
    }
}


$ b $水果是一个空类。这两个代表都有相同的签名。

Fruit is an empty class. Both of these delegates have the same signature.

我似乎没有任何工作。如果我解释了我正在做的事情(提供一些上下文),可能会有所帮助。

I cannot seem to get any of this working. Maybe it would help if I explained what I am trying to do (provide some context).

我想创建一个具有通用静态方法的类,提供一个类型和一个方法回调(像上面的例子)。

I want to create a class that has a generic static method that provides a type and a method callback (like the above example).

我遇到的问题是委托包含一个参数,我不想把它转换成方法回调。例如,我想要这样:

The problem I am having is that the delegate contains a parameter and I don't want to have to cast it within the method callback. For example, I want this:

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

private void AppleHandler(Apple apple)
{

}

而不是这样:

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

private void AppleHandler(Fruit fruit)
{
    Apple apple = (Apple)fruit;
}

这样的事情可能吗?一直在工作几个小时,没有多少运气= /

Is this kind of thing possible? Have been working on it for a few hours without much luck =/

推荐答案

这是你想要的?

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

这篇关于如何将一个动作转换成同一个签名的定义的代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆