为什么更新WCF服务引用会向属性附加数字?

时间:2014-11-24 21:55:11

标签: c# wcf

查看生成的请求的Reference.cs文件,有一个属性:

    [System.Runtime.Serialization.DataMemberAttribute()]
    public TestClass1 TestClass {
        get {
            return this.TestClassField;
        }
        set {
            if ((object.ReferenceEquals(this.TestClassField, value) != true)) {
                this.TestClassField = value;
                this.RaisePropertyChanged("TestClass");
            }
        }
    }

使用另一个属性:

    [System.Runtime.Serialization.DataMemberAttribute()]
    public TestClass TestClass {
        get {
            return this.TestClassField;
        }
        set {
            if ((this.TestClassField.Equals(value) != true)) {
                this.TestClassField = value;
                this.RaisePropertyChanged("TestClass");
            }
        }
    }

引用相同的字段。当我尝试使用此字段时:

var sampleRequest = new SampleRequest();
sampleRequest.TestClass = new global::SampleService.TestClass();

抛出错误:

无法将源类型TestClass转换为TestClass1。

sampleRequest.TestClass具有类型TestClass,而不是引用未悬空属性,而是引用TestClass1。为什么会这样?有没有办法抑制这种行为?

1 个答案:

答案 0 :(得分:1)

我会说你是他们合同的牺牲品。有人装饰了两个具有相同名称的属性(并且基于此生成了引用)。最有可能发生以下情况:

// The original written application had the following class, but then
// deprecated it (maybe they changed around object, changed interfaces,
// who knows. It just got deprecated internally.)
// So, with all the ties in the system, they probably retained the name,
// but renamed it in the contract.
[Obsolete]
[DataContract(Name = "TestClass1")]
public class TextClass // The class formerly known as TestClass
{
}

// This is the refactored TestClass that should be used from here on out.
// They most likely created a new class with a similar name which lent
// itself to being plumbed in a modular fashion (but wanted the same name
// to any service consumers)
[DataContract(Name = "TestClass")]
public class TestClassNew
{
}

// DTO
[DataContract]
public ParentClass
{
    // Keep the old reference (may still have back-references or
    // functionality that hasn't been migrated). However, they should have
    // also renamed the "Name").
    [DataMember(Name = "TestClass")]
    public TestClass TestClass { get; set; }

    // The new object that now shares the same name.
    [DataMember(Name = "TestClass")]
    public TestClassNew TestClassNew { get; set; }
}

在客户端上会产生两个具有相同名称的属性。