[英]Invoke WCF method in Generic Class property with Reflection
我有以下課程:
Public Class WcfClient(Of T)
Private _Cliente As T
Public ReadOnly Property Client As T
Get
Return _Cliente
End Get
End Property
T代表Wcf Channel,其創建方式如下:
Dim channel As New ChannelFactory(Of T)(basicHttpBinding, remoteAddress)
'Set the property
_Cliente = channel.CreateChannel()
現在,通過反思,我正在創建WcfClient的實例,並且我想執行Client屬性內部的Method。
Type tipo = FindInterface(Request.GetFriendlyUrlSegments()[0]);
Type genType = typeof (WcfClient<>).MakeGenericType(tipo);
var client = Activator.CreateInstance(genType);
var clientProp = client.GetType().
GetProperties().Where(p => p.Name == "Client").FirstOrDefault();
if (clientProp != null)
{
var method =clientProp.PropertyType
.GetMethod(Request.GetFriendlyUrlSegments()[1]);
ProcesoBase procesoBase = new ProcesoBase();
foreach (var prop in typeof (ProcesoBase).GetProperties())
{
//Here we have some code to fill ProcesoBase properties
}
}
var result = method.Invoke(clientProp, new object[] { procesoBase });
調用method.Invoke時出現異常的Object does not match target type
我從clientProp變量獲取MethodInfo類,所以我不知道它是如何發生的。
可能是因為生成的Channel類是作為proxy_TransparentProxy類構建的嗎?
好的,我通過使用GetValue而不是GetProperties獲取客戶端屬性來解決此問題:
PropertyInfo p = client.GetType().GetProperty("Client");
MethodInfo m = p.PropertyType.GetMethod(Request.GetFriendlyUrlSegments()[1]);
object clientProp = p.GetValue(client);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.