【问题标题】:Why C# Arrays type IsSerializable property is True?为什么 C# Arrays 类型的 IsSerializable 属性为 True?
【发布时间】:2018-02-14 00:09:41
【问题描述】:

我只是好奇为什么 C# 数组会为其 IsSerializable 属性返回 true。数组没有Serializable属性,也没有实现ISerializable接口,那为什么IsSerializable属性设置为true呢?

当我尝试以下代码时,它会在控制台中输出“True”:

Console.WriteLine (new string[0].GetType().IsSerializable);

输出是:

True

Try it online

我的 .NET 运行时版本是 3.5。

【问题讨论】:

  • @EdPlunkett 我查看了您链接到的文档,但找不到任何似乎适用于该问题的内容。
  • @dahui 没有有用的信息。 This link is correct
  • @BJMyers 好点。
  • @HasanBayat 我正在链接到它,因为它可能会向 OP 解释 IsSerializable 属性是什么

标签: c# .net arrays serialization


【解决方案1】:

Arrays 没有任何Serializable 属性,它们也没有实现ISerializable 接口

Array 类,C# 数组的隐式基类,具有[SerializableAttribute]

[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Array : ICloneable, IList, ICollection, 
    IEnumerable, IStructuralComparable, IStructuralEquatable

(reference)

编译器似乎也将[SerializableAttribute]添加到数组类型本身

foreach (var a in typeof(string[]).GetCustomAttributes(false)) {
    Console.WriteLine(a); // Prints "System.SerializableAttribute"
}

false 传递给GetCustomAttributes 可确保仅返回此类的属性,而不返回其基类的属性。

Demo.

【讨论】:

  • 为什么,它的基类System.Object 也带有[Serializable] 属性?您使用什么版本的运行时让typeof(string[]).GetCustomAttributes(false) 返回该属性?最后一个问题:您的答案是否暗示IsSerializableSystem.Type 对象返回的内容与其所代表的类是否带有[Serializable] 属性之间存在关系?
  • 我试图调查我自己的一些言论。看起来IsSerializable在大多数情况下反映了是否存在[Serializable]属性,但某些枚举类型和委托类型是例外。对我来说,像string[] 这样的数组类型似乎也是例外?该属性不是继承的(如果是,所有类都会继承它,因为它装饰了System.Object,正如我所说的)。
  • @JeppeStigNielsen 感谢您的精彩评论!我也对此进行了调查,看起来该实现在 CLR 的内部很深。演示中的代码在 ideone 上运行,所以我不确定他们使用的是什么版本的运行时。当我在 Microsoft 的最新运行时运行它时,我没有返回任何属性,即使将 true 传递给 GetCustomAttributes 也是如此。在这一点上,我认为将类标记为可序列化是 CLR 的魔法,隐藏在 RuntimeTypeHandle.GetAttributes 方法的本机实现中。不过,我找不到它的来源。
  • 是的。因为class SerializableAttribute 有一个[AttributeUsage],它设置Inherited = false(默认为true),我相信在这种情况下,您是否说将truefalse 传递给GetCustomeAttributes 是无关紧要的。
猜你喜欢
  • 2010-09-22
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 1970-01-01
  • 2012-01-27
  • 2019-07-16
  • 2012-02-28
相关资源
最近更新 更多