我正在处理一个动态实例化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()
调用可能需要很长时间,因此我正在尝试优化代码,通过使用lambda表达式:不要使用 Activator.CreateInstance 或 ConstructorInfo.Invoke,使用编译的 Lambda 表达式:
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: 尝试访问一个不存在的成员。
我在代码中漏掉了什么吗?
谢谢!