C#調用webservice 時如何傳遞實體對象


在webservice端公開一個實體類,然后實例化,賦值,然后再給到webservice,可以實現,但是,即使調用端和service端的實體類完全一致,你也要重新實例化service端的,重新賦值,將此傳回service端。因為,C#是強類型的語言。

當然,你也可以通過下面的方法傳遞實體類,而不用太糾結於賦值了。
在調用端序列化實體對象(實體對象須是可序列化的類):
 
public static byte[] SerializeObject( object pObj)
        {
             if (pObj ==  null)
                 return null;
            System.IO.MemoryStream memoryStream =  new System.IO.MemoryStream();
            BinaryFormatter formatter =  new BinaryFormatter();
            formatter.Serialize(memoryStream, pObj);
            memoryStream.Position = 0;
            byte[] read =  new byte[memoryStream.Length];
            memoryStream.Read(read, 0, read.Length);
            memoryStream.Close();
             return read;
        }
 
在service的調用方法中,接受一個byte[] 參數即可,然后反序列化:
 
public object DeserializeObject( byte[] pBytes)
        {
             object newOjb = null;
             if (pBytes == null)
            {
                 return newOjb;
            }
            System.IO.MemoryStream memoryStream =  new System.IO.MemoryStream(pBytes);
            memoryStream.Position = 0;
            BinaryFormatter formatter =  new BinaryFormatter();
            newOjb = formatter.Deserialize(memoryStream);
            memoryStream.Close();
             return newOjb;
        }
 
然后將object強制轉換成相應的實體類型,就可以直接使用此對象了。
注:在調用端和service端都引用了同一版本的實體程序集.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM