【发布时间】:2023-03-06 03:35:01
【问题描述】:
我遇到了一个(我认为是)服务引用生成问题。
原始类(示例)
[Serializable()]
public class Foo
{
private int _Bar;
public int Bar
{
get { return _Bar; }
set { _Bar = value; }
}
public Foo()
{
this._Bar = 42;
}
}
我发现构造函数使用私有支持字段而不是使用公共设置器很奇怪,所以我重构了这个:
[Serializable()]
public class Foo
{
public int Bar { get; set; }
public Foo()
{
this.Bar = 42;
}
}
我相信这两个似乎足够等效...但是当我重新生成包含对 Foo 的引用的服务引用时...我收到了编译错误。
Foo 中不存在 _Bar 的引用/扩展方法
请注意,这只是我对编译错误的记忆,因为这只是我遇到的一般示例。存在依赖此服务引用的现有代码,它以某种方式引用了 Foo._Bar - 即使它是私有的。
那么...这是预期的行为吗?我重构的类虽然看起来和我一样……以我没想到的方式生成了一个参考类。
我假设因为私有 _Bar 在构造函数中被直接引用,所以即使它是私有的,它也以某种方式与类一起序列化?
我很担心这种行为,因为我在代码库的许多地方都进行了类似的重构 - 我不了解序列化类的工作原理吗?
编辑:
我注意到在 Foo 类上创建的原始参考文件如下所示:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Foo", Namespace="http://schemas.datacontract.org/2004/07/Foo")]
[System.SerializableAttribute()]
public partial class Foo: object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
private int _BarField;
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public int _Bar {
get {
return this._BarField;
}
set {
if ((this._BarField.Equals(value) != true)) {
this._BarField = value;
this.RaisePropertyChanged("_Bar");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
我想我希望 Bar 是原始类的参考文件中的可访问属性,而不是 _Bar - 但在这种情况下,这种假设是不正确的。我在这里缺少什么吗?为什么生成参考文件时使用私有_Bar 作为属性,而不是使用公共Bar 作为私有支持字段的getter 和setter?
【问题讨论】:
-
您是否正在编辑生成的代码并且是
partial类?也许类的另一部分是指原始的_Bar? -
@MickyDuncan 不是部分类,我没有编辑自动生成的代码 :(
标签: c# asp.net wcf serialization