为什么更新 WCF 服务引用会将数字追加到属性

本文关键字:数字 追加 属性 更新 WCF 服务 引用 为什么 | 更新日期: 2023-09-27 18:31:51

查看为请求生成的 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();

抛出错误:

无法将源类型测试类转换为测试类 1。

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

为什么更新 WCF 服务引用会将数字追加到属性

我会

说你成为他们合同的受害者。有人用相同的名称装饰了两个属性(并且正在基于此生成引用)。最有可能发生类似以下情况:

// 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; }
}

这将导致在客户端上具有两个具有相同名称的属性。