Tôi đang làm việc với mã tự động khởi tạo đối tượng SoapHttpClientProtocol
(lớp proxy) và sử dụng đối tượng này để thực hiện cuộc gọi đến WS-Basic I Web Service. Dưới đây là phiên bản đơn giản hóa của mã của tôi:Sử dụng biểu thức Lambda biên dịch thay vì Activator.CreateInstance để khởi tạo đối tượng SoapHttpClientProtocol
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);
}
tôi đã nhận thấy rằng trong một số trường hợp Activator.CreateInstance()
cuộc gọi có thể mất nhiều thời gian, vì vậy tôi đang cố gắng để tối ưu hóa mã by using a lambda expression:
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);
}
Thật không may, mã này không tạo đối tượng thuộc loại callingObject
(thay vào đó nó trả về đối tượng đại diện Func<T>
) và do đó khi cố gắng đặt Url
trong dòng tiếp theo, nó sẽ ngoại lệ:
System.MissingMethodException: Đã cố gắng truy cập một thành viên bị thiếu.
Tôi có thiếu thứ gì đó trong mã của mình không?
Cảm ơn!
Liên kết bị chết theo cách – NStuke