How to convert an action to a defined delegate of the same signature?

后端 未结 3 923
北海茫月
北海茫月 2020-12-19 09:30
class Test
{
    public delegate void FruitDelegate(Fruit f);

    public void Notify(Action del) where T : Fruit
    {
        FruitDelegate f = d         


        
3条回答
  •  别那么骄傲
    2020-12-19 10:20

    is this what you want?

    static void Main(string[] args)
    {
    
        Program p = new Program();
        p.SomeMethod();
    }
    
    public class Fruit
    { }
    
    public class Apple : Fruit { }
    
    public delegate void FruitDelegate(T f) where T : Fruit;
    
    class Test
    {
        public static void Notify(FruitDelegate 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 del = new FruitDelegate(AppleHandler);
        Test.Notify(del);
    }
    

提交回复
热议问题