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.


Not finding it easy to create an Html helper as the ctx passed in is that of the template, and it has no idea of the parent view. Faking the Url is not possible to pass to the GetLocalResourceObject for 2 reasons:

1 if you're using areas, the templates context lies about its virtual url and physical url.

2: you cannot new up a ResourceExpressionBuilder and call ParseExpression on the resource expression using a "fake" url to try and trick the system into thinking the template comes from the folder containing the App_LocalResources holding the required resx.

Gutted!!

As another hack i am going to try adding the templates into the folders using linked items. I'll report back with my findings.

4

2 に答える 2

33

DelegatedCallanyobjectを引数として取るデリゲートが必要です。しかし、foo1あなたが渡しているあなたの関数は、引数DelegatedCallにしか対処できません。stringしたがって、変換はタイプセーフではないため、不可能です。

入力パラメーターは変ですが、コードには共変が必要です。(共分散と反分散の違いを参照してください。)

DelegatedCallジェネリックにすることができます:

DelegatedCall<T>(Action<T> action)

...または任意のデリゲートを取る:

DelegatedCall(Delegate action)

しかし、それを実装するのは見苦しく、反省が必要です。また、コンパイル時に関数にパラメーターが 1 つしかないことも確認しません。

于 2011-01-16T11:32:19.143 に答える
10

分散はそのようには機能しません。あなたが必要だろう

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

4.0 でさえ、すべてのオブジェクトが文字列であるとは信じません。

すべての文字列がオブジェクトであるため、(4.0 では) そうだった場合 (つまりfoo1(object)Action<string>その逆) はおそらく機能することに注意してください。

于 2011-01-16T10:06:57.997 に答える