客户端中的 DataContract 对象 - 只有简单的属性不会因调用而丢失

DataContract objects in client - only simple properties are not getting lost from call to call

我有这个代码,一个使用 DataContract 的服务。 主机建立在网站上。 请注意,服务处于 PerSession 模式:

public interface IService
{
    [OperationContract]
    int GetNewAge(Person person);
}


[DataContract]
public class Person
{
    private int age;
    [DataMember]
    public int Age
    {
        get { return age; }
        set { age = value; }
    }
    [DataMember]
    public int AgeNextYear
    {
        get { return age + 1; }
    }
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IService
{
    public int GetNewAge(Person person)
    {
        return person.AgeNextYear;
    }
}

The Client: Uses the type person:

ServiceClient c = new ServiceClient();
Person person = new Person { Age = 100 };
int curAge = person.Age;
int nextYearAge1 = person.AgeNextYear;
int nextYearAge2 = c.GetNewAge(person);

curAge - 好的。 - 简单 属性 工作正常。

nextYearAge1 - 0,而不是 101

nextYearAge2 - 程序崩溃...

有人可以帮忙吗?非常感谢,Liron。

您的数据合同应该是 data 合同。 AgeNextYear 这样的逻辑 不会被传输,并且没有代理 class 可以使用该逻辑。

如果 WCF 对话的双方都是 C# 并且您使用的是数据协定程序集,则可以这样做。然后简单地删除 AgeNextYear 上的 [DataMember] 属性就可以了,因为逻辑是通过公共合约程序集共享的。

示例:

[DataContract]
public class Person
{
    // this is plain data. It can be transfered back and forth,
    // other languages and frameworks will have no problem 
    // building proxy classes for it
    [DataMember]
    public int Age { get; set; }

    // this is not data. There is no data, there only is a calculation. 
    // That's logic. Logic cannot be transfered. Lets say your age is 18, 
    // then this is 19. But the point that this is not a fixed value of 19, 
    // but actually Age + 1, cannot be transfered. It's not data. It should 
    // not be part of the contract if you want this to be usable as a 
    // generic web service.
    [DataMember]
    public int AgeNextYear
    {
        get { return Age + 1; }
    }
}