关于委托方法中,我怎么转换对象的问题。
我在调试代码的时候,都能看到func.Target 里面的SG.SGService.WCFRefObj;对象,为什么转换出来就是空的呢?
SG.SGService.WCFRefObj wcfRefObj = func.Target as SG.SGService.WCFRefObj;
这个转换出来是null的。
调试代码的图片如下。
代码如下
using System;
using System.Linq;
using SG.com.ll.Config;
using System.ServiceModel;
using System.Collections.Generic;
using SG.SGService;
using System.Reflection;
namespace SG.com.ll.Method
{
/// <summary>
/// Wcf服务调用辅助类
/// </summary
public static class WCFHelper<TChannel> where TChannel : ICommunicationObject, new()
{
private static Dictionary<string, TChannel> _ChannelDic = new Dictionary<string, TChannel>();
private static object _Lockhelper = new object();
private static TResult TryFunc<TResult>(Func<TChannel, TResult> func, TChannel channel, ref bool isSuccess, ref string msg)
{
string tChannelName = typeof(TChannel).FullName;
try
{
isSuccess = true;
return func(channel);
}
catch (CommunicationException ex)
{
channel.Abort();
lock (_Lockhelper)
_ChannelDic.Remove(tChannelName);
isSuccess = false;
msg = ex.Message;
return default(TResult);
}
catch (TimeoutException ex)
{
channel.Abort();
lock (_Lockhelper)
_ChannelDic.Remove(tChannelName);
isSuccess = false;
msg = ex.Message;
return default(TResult);
}
catch (Exception ex)
{
channel.Abort();
lock (_Lockhelper)
_ChannelDic.Remove(tChannelName);
isSuccess = false;
msg = ex.Message;
return default(TResult);
}
}
private static TChannel GetChannel()
{
TChannel instance;
string tChannelName = typeof(TChannel).FullName;
if (!_ChannelDic.ContainsKey(tChannelName))
{
lock (_Lockhelper)
{
instance = Activator.CreateInstance<TChannel>();
_ChannelDic.Add(tChannelName, instance);
}
}
else
{
instance = _ChannelDic[tChannelName];
}
if (instance.State != CommunicationState.Opened && instance.State != CommunicationState.Opening)
instance.Open();
return instance;
}
//<summary>
//直接调用,无返回值
//</summary>
public static void Invoke(Action<TChannel> action)
{
TChannel instance = GetChannel();
bool isSuccess = true;
string refMsg = string.Empty;
TryFunc(client =>
{
action(client);
return (object)null;
}, instance, ref isSuccess, ref refMsg);
}
/// <summary>
/// 有返回值的调用
/// </summary>
public static TResult Invoke<TResult>(Func<TChannel, TResult> func)
{
TChannel instance = GetChannel();
TResult returnValue = default(TResult);
bool isSuccess = true;
string refMsg = string.Empty;
returnValue = TryFunc(func, instance, ref isSuccess, ref refMsg);
//获取对象转换
SG.SGService.WCFRefObj wcfRefObj = func.Target as SG.SGService.WCFRefObj;
if (wcfRefObj.IsSuccess)
{
string str = "WCF内部方法返回正确";
}
else
{
string str = String.Format("WCF内部方法返回失败,失败代码{0}失败的详情{1}", wcfRefObj.ErrorCode, wcfRefObj.Message);
}
return returnValue;
}
}
}
WCF方法调用
WCFRefObj wcfRefObj = new WCFRefObj();
NEWWCFHelper<SGServiceClient>.Invoke((client, WCFRefObj) => client.ChenckDevice(1001, ref wcfRefObj));