我有这种情况,我在C#中使用的Web服务方法返回一个Business对象,当使用以下代码调用webservice方法时,我在reference.cs类中得到异常"无法将ContactInfo类型的对象强制转换为类型ContactInfo"的网络参考
码:
ContactInfo contactInfo = new ContactInfo();
Contact contact = new Contact();
contactInfo = contact.Load(this.ContactID.Value);
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激.
Nei*_*ell 10
这是因为其中一个ContactInfo
对象是Web服务代理,并且位于不同的命名空间中.
这是asmx风格的Web服务的一个已知问题.在过去,我已经实现了自动浅拷贝来解决它(这里是如何,但如果我再次这样做,我可能会看看AutoMapper).
例如,如果您有一个包含以下类的程序集:
MyProject.ContactInfo
Run Code Online (Sandbox Code Playgroud)
并从web方法返回它的实例:
public class DoSomethingService : System.Web.Services.WebService
{
public MyProject.ContactInfo GetContactInfo(int id)
{
// Code here...
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当您将Web引用添加到客户端项目时,实际上是这样的:
MyClientProject.DoSomethingService.ContactInfo
Run Code Online (Sandbox Code Playgroud)
这意味着如果在您的客户端应用程序中调用Web服务来获取a ContactInfo
,则会出现以下情况:
namespace MyClientProject
{
public class MyClientClass
{
public void AskWebServiceForContactInfo()
{
using (var service = new DoSomethingService())
{
MyClientProject.DoSomethingService.ContactInfo contactInfo = service.GetContactInfo(1);
// ERROR: You can't cast this:
MyProject.ContactInfo localContactInfo = contactInfo;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它是在我使用我的ShallowCopy
班级的最后一行:
namespace MyClientProject
{
public class MyClientClass
{
public void AskWebServiceForContactInfo()
{
using (var service = new DoSomethingService())
{
MyClientProject.DoSomethingService.ContactInfo contactInfo = service.GetContactInfo(1);
// We actually get a new object here, of the correct namespace
MyProject.ContactInfo localContactInfo = ShallowCopy.Copy<MyClientProject.DoSomethingService.ContactInfo, MyProject.ContactInfo>(contactInfo);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意
这仅适用,因为代理类和"真实"类具有完全相同的属性(一个是由Visual Studio生成的).
归档时间: |
|
查看次数: |
10719 次 |
最近记录: |