type
型から派生したことがわかっている があるとしますDelegate
。任意のパラメーターを受け入れ、正しい戻り値の型のオブジェクトを返す匿名デリゲートをラップするこの型のオブジェクトを作成したいと思います。
var retType = type.GetMethod("Invoke").ReturnType;
var obj = Delegate.CreateDelegate(type, delegate(object[] args) {
...
if (retType != typeof(void))
... somehow create object of type retType and return it ...
});
2 番目の引数としてCreateDelegate
aが必要なため、明らかにこれはコンパイルされません。MethodInfo
どうすればこれを正しく行うことができますか?
更新:私が達成しようとしていることに関するもう少しの情報。ブラウザのクライアントと C# のサーバーの 2 つのアプリケーションが実行されています。ブラウザーは、引数を JSON にシリアル化し、ネットワーク経由で (RPC のように) 呼び出しを送信することにより、サーバー側でリモート関数を呼び出すことができます。これは既に機能していますが、コールバックのサポートを追加したいと考えています。例えば:
JavaScript (クライアント):
function onNewObject(uuid) { console.log(uuid); }
server.notifyAboutNewObjects(onNewObject);
C# (サーバー):
void notifyAboutNewObjects(Action<string> callback) {
...
callback("new-object-uuid");
...
}
ミドルウェア コードはブラウザーからの呼び出しを受け取り、callback
実際に呼び出しをcallback
ブラウザーに送り返し、完了するまでスレッドをブロックする偽のデリゲートを生成する必要があります。送信/受信のコードは既にあります。すべての引数を配列に入れ、送信コードに渡すだけの汎用デリゲートを生成する方法に固執しています。
更新:誰かが実行時にそのようなデリゲートを生成するコードを記述できる場合 (たとえば、DynamicMethodを使用)、有効な答えと見なします。これを行う方法を学ぶのに十分な時間がないので、経験豊富な誰かがこのコードを十分に迅速に記述できることを願っています。基本的に、コードは任意のデリゲート パラメータ (リストと型は実行時に使用可能) を取り、それらを配列に入れ、ジェネリック メソッドを呼び出す必要があります。ジェネリック メソッドは常に を返します。object
これは、それぞれの戻り値の型にキャストするか、関数が を返す場合は無視する必要がありますvoid
。
更新:必要なものを示す小さなテスト プログラムを作成しました。
using System;
using System.Reflection;
namespace TestDynamicDelegates
{
class MainClass
{
// Test function, for which we need to create default parameters.
private static string Foobar(float x, Action<int> a1, Func<string, string> a2) {
a1(42);
return a2("test");
}
// Delegate to represent generic function.
private delegate object AnyFunc(params object[] args);
// Construct a set of default parameters to be passed into a function.
private static object[] ConstructParams(ParameterInfo[] paramInfos)
{
object[] methodParams = new object[paramInfos.Length];
for (var i = 0; i < paramInfos.Length; i++) {
ParameterInfo paramInfo = paramInfos[i];
if (typeof(Delegate).IsAssignableFrom(paramInfo.ParameterType)) {
// For delegate types we create a delegate that maps onto a generic function.
Type retType = paramInfo.ParameterType.GetMethod("Invoke").ReturnType;
// Generic function that will simply print arguments and create default return value (or return null
// if return type is void).
AnyFunc tmpObj = delegate(object[] args) {
Console.WriteLine("Invoked dynamic delegate with following parameters:");
for (var j = 0; j < args.Length; j++)
Console.WriteLine(" {0}: {1}", j, args[j]);
if (retType != typeof(void))
return Activator.CreateInstance(retType);
return null;
};
// Convert generic function to the required delegate type.
methodParams[i] = /* somehow cast tmpObj into paramInfo.ParameterType */
} else {
// For all other argument type we create a default value.
methodParams[i] = Activator.CreateInstance(paramInfo.ParameterType);
}
}
return methodParams;
}
public static void Main(string[] args)
{
Delegate d = (Func<float, Action<int>,Func<string,string>,string>)Foobar;
ParameterInfo[] paramInfo = d.Method.GetParameters();
object[] methodParams = ConstructParams(paramInfo);
Console.WriteLine("{0} returned: {1}", d.Method.Name, d.DynamicInvoke(methodParams));
}
}
}