简体   繁体   中英

Cannot convert method group '' to non-delegate type 'System.Delegate'. Did you intend to invoke the method?

I'm trying to store a function reference in a Delegate type for later use.

Here's what I'm doing:

class Program
{
    static void Test()
    {

    }

    static void Main(string[] args)
    {
        Delegate t= (Delegate)Test;
    }
}

In this I'm getting following error:

Cannot convert method group 'Test' to non-delegate type 'System.Delegate'.
Did you intend to invoke the method?

Why is this happening?

You really shouldn't ever use the type Delegate to store a delegate. You should be using a specific type of delegate.

In almost all cases you can use Action or Func as your delegate type. In this case, Action is appropriate:

class Program
{
    static void Test()
    {

    }

    static void Main(string[] args)
    {
        Action action = Test;

        action();
    }
}

You can technically get an instance of Delegate by doing this:

Delegate d = (Action)Test;

But actually using a Delegate , as opposed to an actual specific type of delegate, such as Action , will be hard, since the compiler will no longer know what the signature of the method is, so it doesn't know what parameters should be passed to it.

What you are trying to do here is cast the method group Test to something. As per the spec, the only legal cast for a method group is casting it into a delegate type. This can be done either explicitly:

var t = (Delegate)Test;

or implicitly:

Delegate t = Test;

However, as the documentation says, System.Delegate itself is... not a delegate type:

The Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. It is also not permissible to derive a new type from a delegate type. The Delegate class is not considered a delegate type; it is a class used to derive delegate types.

The compiler detects this and complains.

If you want to cast a method group to a delegate you will have to specify a delegate type with a compatible signature (in this case, Action ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM