Delegate Covariance Confusion Conundrum!

前端 未结 6 1986
孤街浪徒
孤街浪徒 2021-01-02 14:47

Why does this not work? Do I not understand delegate covariance correctly?

public delegate void MyDelegate(object obj)

public class MyClass
{
    public MyC         


        
6条回答
  •  我在风中等你
    2021-01-02 15:30

    You need to use a generic.

    EDIT: Why? Because as another poster noted, Object and SomeObject do not equate to the same thing as Object may not be SomeObject. This is the whole point of Generics in the language.

    public delegate void MyDelegate(T obj)
    
    public class MyClass
    {
        public MyClass()
        {
            _delegate = MyMethod;
        }
    
        private MyDelegate _delegate;
    
        public void MyMethod(SomeObject obj)
        {
        }
    }
    

提交回复
热议问题