0

インターフェイスを使用してシリアル化/逆シリアル化できないことは知っていますが、私が見ている動作に混乱しています。

デシリアライズしてインターフェイスにキャストバックすると、一部のプロパティがnullになります。しかし、具象型にキャストバックすると、同じプロパティに値がありますか?

したがって、このXML(簡潔にするために短縮)を考えると、次のようになります。

<Page>
  <ComponentPresentations>
    <ComponentPresentation>
      <Component>
        <Categories>
          <Category>
            <Id>tcm:35-540-512</Id>

で逆シリアル化

var serializer = new XmlSerializer(typeof(Page));
page = (IPage)serializer.Deserialize(reader);

page.ComponentPresentations[0].Component.Categories <-- is null

しかし、私がタイプにキャストバックすると、

var serializer = new XmlSerializer(typeof(Page));
page = (Page)serializer.Deserialize(reader);

page.ComponentPresentations[0].Component.Categories <-- is not null!

ページタイプは、インターフェイスのカテゴリプロパティと非インターフェイスプロパティを公開します-シリアル化インターフェイスの問題を回避すると思います。

public List<Category> Categories { get; set; }
[XmlIgnore]
IList<ICategory> IComponent.Categories
{
    get { return Categories as IList<ICategory>; }
}

これは、インターフェイスプロパティがセッターを公開していないためですか?

4

1 に答える 1

1

いいえ。問題は、反変性List<T>がおよびでサポートされていないことIList<T>です。ここに良いリファレンスがあります。


この簡単なコードを見てください:

public interface IMyInterface
{

}

public class MyImplementation : IMyInterface
{

}

List<MyImplementation> myImplementations = new List<MyImplementation>();
Console.WriteLine(myImplementations as IList<IMyInterface> == null); // OUTPUT: true!!

ご覧のとおり、Categories as IList<ICategory>常に null になります。間Categories as IList<Category>はOKです。

連載とは関係ありません

于 2012-04-11T15:38:09.590 に答える