6

オブジェクト (プロキシ クラス)を動的にインスタンス化SoapHttpClientProtocolし、このオブジェクトを使用して WS-Basic I Web サービスを呼び出すコードを扱っています。これが私のコードの簡略版です:

public override object Call(Type callingObject,
string method, object[] methodParams, string URL)
{
    MethodInfo requestMethod = callingObject.GetMethod(method);

    //creates an instance of SoapHttpClientProtocol
    object instance = Activator.CreateInstance(callingObject);

    //sets the URL for the object that was just created 
    instance.GetType().InvokeMember("Url", 
    BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, null,
    instance,
    new object[1] {URL});

    return requestMethod.Invoke(instance, methodParams); 
}

Activator.CreateInstance()呼び出しにかなりの時間がかかる場合があることに気付いたので、ラムダ式を使用してコードを最適化しようとしています。

public override object Call(Type callingObject,
string method, object[] methodParams, string URL)
{
    MethodInfo requestMethod = callingObject.GetMethod(method);

    //creates an instance of SoapHttpClientProtocol using compiled Lambda Expression
    ConstructorInfo constructorInfo = callingObject.GetConstructor(new Type[0]);
    object instance = Expression.Lambda(Expression.New(constructorInfo)).Compile();

    //sets the URL for the object that was just created 
    instance.GetType().InvokeMember("Url", 
    BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, null,
    instance,
    new object[1] {URL});

    //calls the web service
    return requestMethod.Invoke(instance, methodParams); 
}

残念ながら、このコードは型のオブジェクトを作成しませんcallingObject(代わりにデリゲート オブジェクトを返しFunc<T>ます)。そのため、次の行で を設定しようとするとUrl、例外がスローされます。

System.MissingMethodException: 不足しているメンバーにアクセスしようとしました。

コードに何か不足していますか?

ありがとう!

4

2 に答える 2

3

このExpression.Lambda(Expression.New(constructorInfo)).Compile()部分は、storedinパラメーターのコンストラクターをラップするデリゲートをFunc<T>返します。そのコンストラクターを実際に呼び出すには、それを呼び出す必要があります。TypecallingObject

Delegate delegateWithConstructor = Expression.Lambda(Expression.New(constructorInfo)).Compile();
object instance = delegateWithConstructor.DynamicInvoke();

ただし、メソッド名を単純な文字列として渡し、パラメータをオブジェクトとして渡すため、コンパイル時の型チェックがすべて失われるため、長期的には非常に奇妙で壊れやすいように見えます。なぜあなたはそれをする必要がありますか?

于 2012-07-26T19:27:43.200 に答える