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

后端 未结 3 917
北海茫月
北海茫月 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:06

    There is good reason you cannot do this. Suppose the rest of your method was:

    class Test
    {
        public delegate void FruitDelegate(Fruit f);
    
        public void Notify(Action del) where T : Fruit
        {
            FruitDelegate f = del; 
            f(new Banana());  //should be legal, but del may be Action
        }
    }
    

    That would definitely not work, so the compiler is correct here.

提交回复
热议问题