日期:2014-05-17  浏览次数:21146 次

WCF使用泛型方法的问题
C# code

/// <summary>
        /// 获取得到值以后的 泛型数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="SQL"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<T> getModelList<T>(string SQL, List<string> list)where T:class,new()
        {
            try
            {
                List<T> Mlist = new List<T>();
                IDataReader dr = getDataReader(SQL, list);
                while (dr.Read())
                {
                    T obj = new T();
                    obj = this.LoadFromReader<T>(dr);
                    Mlist.Add(obj);
                }
                return Mlist;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


WCF编译时,出现如下错误
类型“System.Collections.Generic.List`1[T]”无法作为架构类型被导出,因为它是一种开放的泛型类型。泛型类型仅可以在其所有的泛型参数类型均为实际类型时才可以被导出。 

寻求解决办法

------解决方案--------------------
加[ServiceKnownTypeAttribute]
------解决方案--------------------
传个Type再反射生成不行么?
------解决方案--------------------
统一出来一个INTERFACE,让T限制在此INTERFACE内。然后加SERVICEKNOWNTYPEATTRIBUTE就行了。
------解决方案--------------------
WCF不能使用泛型方法,不支持。只能使用变通的方法实现,传递Type参数代表T的类型。

------解决方案--------------------
楼主人呢?
要不要帮你把那个泛型方法改写成可以给WCF调用的非泛型方法形式,且功能不变?
------解决方案--------------------
范型方法。用代码方式实现WCF配置
 
public class ConManager
{
NetTcpBinding netTcpBinding = null;
ServiceEndpoint serviceEndpoint = null;
EndpointAddress endpointAddress = null;
InstanceContext instanceContext = null;
public DuplexChannelFactory<T> WCFconfig<T>(long maxReceivedMessageSize, TransferMode transferMode)
{
netTcpBinding = new NetTcpBinding();
netTcpBinding.MaxReceivedMessageSize = maxReceivedMessageSize;
netTcpBinding.TransferMode = transferMode;
ContractDescription cd = ContractDescription.GetContract(typeof(T));

serviceEndpoint = new ServiceEndpoint(cd);
serviceEndpoint.Address = new EndpointAddress("");
serviceEndpoint.Binding = netTcpBinding;


instanceContext = new InstanceContext(this);
DuplexChannelFactory<T> factory = new DuplexChannelFactory<T>(instanceContext, serviceEndpoint);
return factory;
}
}
------解决方案--------------------
WCF能支持泛型吗?lz解决了上来吱一声。
------解决方案--------------------
楼主 能否将你的this.LoadFromReader<T>(dr);方法粘贴出来
------解决方案--------------------
我觉得是不太可能的,因为参数和返回值需要在wsdl中描述,不确定的话,也就没有办法描述了。
------解决方案--------------------
抱歉,最近太忙了,还要去医院挂水,没什么时间。

方案已经设计好,下面给你代码:
C# code

public IList getModelList(string type, string SQL, List<string> list)
{
    try
    {
        IList Mlist = new List<object>();
        IDataReader dr = getDataReader(SQL, list);
        while (dr.Read())
        {
            object obj = this.GetType().GetMethods().First((p) => p.IsGenericMethod && p.Name == "LoadFromReader").MakeGenericMethod(Helper.types[type]).Invoke(this, new object[] { dr });
            Mlist.Add(obj);
        }
        return Mlist;
    }
    catch