. net:相同的实体类在Web和Web服务之间是冲突的
本文关键字:Web 服务 之间 冲突 实体 net | 更新日期: 2023-09-27 17:50:51
这是我的方案结构,有3个项目
.NET 3.5 with Visual Studio 2010 Environment
1. 库项目,用于定义普通类(只有属性,没有任何方法)名称为"Entity"
2. Web应用项目名称为"MyWeb"
3.Web服务项目名称为"MyServices"
我在"Entity"
namespace MyUtil
{
public class Message
{
public int Key { get; set; }
public string Message { get; set; }
public object Value { get; set; }
}
}
下面是从"MyWeb"调用web服务方法的代码。
MyServices service = new MyServices();
MyUtil.Message message = service.GetMessage();
无法编译。仍然是notify error
不能转换MyUtil。Message to MyWe.MyWebService.Message
这里是工作代码
MyServices service = new MyServices();
MyWeb.MyWebService.Message message = service.GetMessage();
问题是我不能使用MyWeb.MyWebService.Message(从web服务返回值)传递数据到另一个web方法。
所以我需要知道,如何在Web和Web服务之间使用相同的实体类。它不能相互传递。这个很难用,有解决方法吗?
在我最近的研究中,我发现我必须将所有实体定义为共享类型,这里是如何
http://technico.qnownow.com/how-to-share-objects-types-between-multiple-web-services/
我已经尝试了很多次,没有任何类的输出文件夹。有人发现这个问题吗?以及如何修复它。
期待帮助,谢谢。
你可以在MyWeb.MyWebService.Message中定义一个隐式/显式操作符,允许你从一个类型转换到另一个类型。如果我们假设你的其他类型看起来相同,你可以这样写:
public static explicit operator MyUtil.Message(MyWeb.MyWebService.Message other)
{
return new MyUtil.Message
{
Key = other.Key,
Message = other.Message,
Value = other.Message
};
}
然后转换你的类型:
MyUtil.Message message = (MyUtil.Message)service.GetMessage();
如果使用隐式操作符而不是显式操作符,也可以摆脱强制转换。但我不建议这样做,因为这可能会在未来的程序中造成混乱。当然,最简单的方法是编写一个转换函数。
这就是将属性值从一个对象克隆到另一个对象的代码(如果名称相同,您还可以检查属性的类型)
public TCloned CloneProperties<TSource, TCloned>(TSource sourceObj)
{
var propertoiesToClone = typeof(TCloned).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
var clonedInstance = (TCloned)Activator.CreateInstance(typeof(TCloned));
var sourceProperties = typeof(TSource).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
foreach (var prop in propertoiesToClone)
{
var appropriatePropery = sourceProperties.SingleOrDefault(p => p.Name == prop.Name);
if (appropriatePropery != null)
{
prop.SetValue(clonedInstance, appropriatePropery.GetValue(sourceObj));
}
}
return clonedInstance;
}
并像这样使用
MyUtil.Message message = CloneProperties<MyWeb.MyWebService.Message, MyUtil.Message>(service.GetMessage())