- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
XmlSerializer
正在调用 IList<T>.Add()
在我的课上,我不明白为什么。
我有一个自定义类(层次结构中的几个类之一),其中包含我使用 XmlSerializer
与 XML 相互转换的数据。 .在我以前的代码版本中,这些类没有实现任何接口(interface),XML 序列化和反序列化似乎都按预期工作。
我现在正在编写一些使用此类中包含的数据的其他代码,我认为如果我可以通过 IList<T>
访问数据会很有帮助。接口(interface),所以我修改了我的类来实现该接口(interface)。 (本例中的“T”是我的另一个自定义类。)这不涉及向该类添加任何新字段;我实现了所有 required methods and properties就已经存储的数据而言。
我希望这不会以任何方式影响序列化。但是,当将 XML 数据反序列化到我的类中时,现在有些东西正在调用新的 Add()
。我作为 IList<T>
的一部分实现的方法接口(interface)(这是一个问题,因为这个特定列表 IsReadOnly
等 Add()
抛出 NotSupportedException
)。
即使我的类的 XML 节点只是 <myClass/>
也会发生这种情况没有任何 XML 属性或子元素; XmlSerializer
显然仍在创建一个新的 myOtherClass
(未在 XML 文档中的任何地方命名)并尝试 Add()
它到 myClass
.
我在这方面搜索信息时遇到问题,因为大多数问题都涉及 XmlSerializer
和 IList<T>
似乎涉及人们试图序列化/反序列化 IList<T>
类型的变量.那不是我的情况;我没有 IList<T>
类型的变量代码中的任何位置。如果我不实现 IList<T>
,我的类序列化和反序列化就很好了界面。
谁能给我解释一下为什么XmlSerializer
正在调用 IList<T>.Add()
在我的课上,和/或如何让它停止?
理想情况下,建议应与最终在 Unity3d (.NET 2.0) 中运行的此代码兼容。
最佳答案
XmlSerializer
要求所有集合都有一个 Add()
方法,如 documentation 中所述:
The XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. A class that implements IEnumerable must implement a public
Add
method that takes a single parameter. TheAdd
method's parameter must be of the same type as is returned from theCurrent
property on the value returned fromGetEnumerator
, or one of that type's bases. A class that implements ICollection (such as CollectionBase) in addition to IEnumerable must have a publicItem
indexed property (indexer in C#) that takes an integer, and it must have a publicCount
property of type integer. The parameter to theAdd
method must be the same type as is returned from theItem
property, or one of that type's bases. For classes that implement ICollection, values to be serialized are retrieved from the indexedItem
property, not by callingGetEnumerator
.
此外,如果一个集合有自己的可设置属性,这些将不会被序列化。这也在 docs 中阐明。 :
The following items can be serialized using the XmLSerializer class:
- Classes that implement ICollection or IEnumerable: Only collections are serialized, not public properties.
要了解这在实践中如何发挥作用,请考虑以下类(class):
namespace V1
{
// https://stackoverflow.com/questions/31552724/how-why-does-xmlserializer-treat-a-class-differently-when-it-implements-ilistt
public class Vector2
{
public double X { get; set; }
public double Y { get; set; }
public Vector2() { }
public Vector2(double x, double y)
: this()
{
this.X = x;
this.Y = y;
}
public double this[int coord]
{
get
{
switch (coord)
{
case 0:
return X;
case 1:
return Y;
default:
throw new ArgumentOutOfRangeException();
}
}
set
{
switch (coord)
{
case 0:
X = value;
break;
case 1:
Y = value;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
}
如果我将其序列化为 XML,我会得到:
<Vector2>
<X>1</X>
<Y>2</Y>
</Vector2>
现在假设我想要一个实现了 IList<double>
的新版本.我添加接口(interface)并实现它,为调整列表大小的所有方法抛出异常:
namespace V2
{
// https://stackoverflow.com/questions/31552724/how-why-does-xmlserializer-treat-a-class-differently-when-it-implements-ilistt
public class Vector2 : V1.Vector2, IList<double>
{
public Vector2() : base() { }
public Vector2(double x, double y) : base(x, y) { }
#region IList<double> Members
public int IndexOf(double item)
{
for (var i = 0; i < Count; i++)
if (this[i] == item)
return i;
return -1;
}
public void Insert(int index, double item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
#endregion
#region ICollection<double> Members
public void Add(double item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(double item)
{
return IndexOf(item) >= 0;
}
public void CopyTo(double[] array, int arrayIndex)
{
foreach (var item in this)
array[arrayIndex++] = item;
}
public int Count
{
get { return 2; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(double item)
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable<double> Members
public IEnumerator<double> GetEnumerator()
{
yield return X;
yield return Y;
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
现在如果我序列化 XML,我得到:
<ArrayOfDouble>
<double>1</double>
<double>2</double>
</ArrayOfDouble>
如您所见,它现在序列化为 double 值的集合,具有可设置的属性 X
和 Y
省略了。然后,反序列化时,Add()
方法将被调用,而不是 X
的 set 方法和 Y
,并抛出异常。
如果我尝试执行 IReadOnlyList<double>
而不是 IList<double>
, XmlSerializer
由于缺少 Add()
,构造函数现在抛出异常方法。
示例 fiddle .
强行没办法XmlSerializer
将集合视为一个简单的对象,而不是 implement IXmlSerializable
和 do it manually ,这是相当繁重的。 ( 有一个 DataContractSerializer
的变通方法,即应用 [DataContract]
而不是 [CollectionDataContract]
—— 但是 DataContractSerializer
直到 .Net 3.5 才被引入,所以它被淘汰了。)
而不是实现 IList<T>
,您可能只想引入一个扩展方法来遍历类中的值,如下所示:
public static class Vector2Extensions
{
public static IEnumerable<double> Values(this Vector2 vec)
{
if (vec == null)
throw new ArgumentNullException();
yield return vec.X;
yield return vec.Y;
}
}
关于c# - XmlSerializer 在实现 IList<T> 时如何/为什么以不同方式对待类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31552724/
我有 table 像这样 -------------------------------------------- id size title priority
我的应用在不同的 Activity (4 个 Activity )中仅包含横幅广告。所以我的疑问是, 我可以对所有横幅广告使用一个广告单元 ID 吗? 或者 每个 Activity 使用不同的广告单元
我有任意(但统一)数字列表的任意列表。 (它们是 n 空间中 bin 的边界坐标,我想绘制其角,但这并不重要。)我想生成所有可能组合的列表。所以:[[1,2], [3,4],[5,6]] 产生 [[1
我刚刚在学校开始学习 Java,正在尝试自定义控件和图形。我目前正在研究图案锁,一开始一切都很好,但突然间它绘制不正确。我确实更改了一些代码,但是当我看到错误时,我立即将其更改回来(撤消,ftw),但
在获取 Distinct 的 Count 时,我在使用 Group By With Rollup 时遇到了一个小问题。 问题是 Rollup 摘要只是所有分组中 Distinct 值的总数,而不是所有
这不起作用: select count(distinct colA, colB) from mytable 我知道我可以通过双选来简单地解决这个问题。 select count(*) from (
这个问题在这里已经有了答案: JavaScript regex whitespace characters (5 个回答) 2年前关闭。 你能解释一下为什么我会得到 false比较 text ===
这个问题已经有答案了: 奥 git _a (56 个回答) 已关闭 9 年前。 我被要求用 Javascript 编写一个函数 sortByFoo 来正确响应此测试: // Does not cras
所以,我不得不说,SQL 是迄今为止我作为开发人员最薄弱的一面。也许我想要完成的事情很简单。我有这样的东西(这不是真正的模型,但为了使其易于理解而不浪费太多时间解释它,我想出了一个完全模仿我必须使用的
这个问题在这里已经有了答案: How does the "this" keyword work? (22 个回答) 3年前关闭。 简而言之:为什么在使用 Objects 时,直接调用的函数和通过引用传
这个问题在这里已经有了答案: 关闭 12 年前。 Possible Duplicate: what is the difference between (.) dot operator and (-
我真的不明白这里发生了什么但是: 当我这样做时: colorIndex += len - stopPos; for(int m = 0; m < len - stopPos; m++) { c
思考 MySQL 中的 Group By 函数的最佳方式是什么? 我正在编写一个 MySQL 查询,通过 ODBC 连接在 Excel 的数据透视表中提取数据,以便用户可以轻松访问数据。 例如,我有:
我想要的SQL是这样的: SELECT week_no, type, SELECT count(distinct user_id) FROM group WHERE pts > 0 FROM bas
商店表: +--+-------+--------+ |id|name |date | +--+-------+--------+ |1 |x |Ma
对于 chrome 和 ff,当涉及到可怕的 ie 时,这个脚本工作完美。有问题 function getY(oElement) { var curtop = 0; if (oElem
我现在无法提供代码,因为我目前正在脑海中研究这个想法并在互联网上四处乱逛。 我了解了进程间通信和使用共享内存在进程之间共享数据(特别是结构)。 但是,在对保存在不同 .c 文件中的程序使用 fork(
我想在用户集合中使用不同的功能。在 mongo shell 中,我可以像下面这样使用: db.users.distinct("name"); 其中名称是用于区分的集合字段。 同样我想要,在 C
List nastava_izvjestaj = new List(); var data_context = new DataEvidencijaDataContext();
我的 Rails 应用程序中有 Ransack 搜索和 Foundation,本地 css 渲染正常,而生产中的同一个应用程序有一个怪癖: 应用程序中的其他内容完全相同。 我在 Chrome 和 Sa
我是一名优秀的程序员,十分优秀!