52

I have created the following function:

public void DelegatedCall(Action<Object> delegatedMethod)

And defined the following method

public void foo1(String str) { }

However, when I try to call DelegateCall with foo1:

DelegatedCall(foo1);

...I get the following compiler error:

Argument 1: cannot convert from 'method group' to 'System.Action<object>'

What is the reason for this error and how can I correct it? Unfortunately, casting foo1 to Action is not an option.


Variance doesn't work that way around; you would need

DelegatedCall(obj => foo1((string)obj));

As even in 4.0 it won't believe that every object is a string.

Note that if it was foo1(object) and Action<string> (i.e. the other way around) it probably would work (in 4.0), since every string is an object.

4

2 回答 2

33

DelegatedCall expects a delegate that takes any object as an argument. But your function foo1 that you are passing to DelegatedCall can only cope with a string argument. So, the conversion isn't type-safe and thus is not possible.

Input parameters are contra-variant, but your code needs covariance. (See Difference between Covariance & Contra-variance.)

You can make DelegatedCall generic:

DelegatedCall<T>(Action<T> action)

...or have it take any delegate:

DelegatedCall(Delegate action)

But then implementing it is ugly and requires reflection. It also doesn't verify that the function has only one parameter at compile-time.

于 2011-01-16T11:32:19.143 回答
10

方差不是那样工作的。你需要

DelegatedCall(obj => foo1((string)obj));

即使在 4.0 中,它也不会相信每个对象都是字符串。

请注意,如果它是foo1(object)并且Action<string>(即相反)它可能会起作用(在 4.0 中),因为每个字符串都是一个对象。

于 2011-01-16T10:06:57.997 回答