親クラスTestから子クラス、Test1,Test2を作成し、
List<Test>のコレクションに追加し、
そのコレクションをXMLシリアライズすると
エラーになります。
おそらくクラスが違うからだと思うのですが、
子クラスでもシリアライズできるようになりませんか?
C#
1 2 3 /// <summary> 4 /// 親クラス 5 /// </summary> 6 public class Test { 7 public Test () { 8 9 } 10 public int MyProperty { get; set; } 11 12 } 13 14 /// <summary> 15 /// 子クラスその1 16 /// </summary> 17 public class Test1:Test { 18 public Test1 () { 19 20 } 21 public int MyProperty1 { get; set; } 22 23 } 24 25 /// <summary> 26 /// 子クラスその2 27 /// </summary> 28 public class Test2 : Test { 29 public Test2 () { 30 31 } 32 public int MyProperty2 { get; set; } 33 34 } 35 36 /// <summary> 37 /// コレクション 38 /// </summary> 39 public class TestList:List<Test> { 40 41 public TestList () { 42 Add( new Test() ); 43 Add( new Test1() ); //ここの2行をnew Test() ならエラーにならない。 44 Add( new Test2() ); 45 } 46 47 } 48 49
上記のようなクラスがあって、
(実際はもっと複雑ですが…)
これをシリアライズで保存しようとすると、
C#
1 public void sample() { 2 3 //保存先のファイル名 4 string fileName = @"C:\sample.xml"; 5 6 TestList test = new TestList(); 7 8 System.Xml.Serialization.XmlSerializer serializer = 9 new System.Xml.Serialization.XmlSerializer( typeof( TestList ) ); 10 11 System.IO.StreamWriter sw = new System.IO.StreamWriter( 12 fileName , false , new System.Text.UTF8Encoding( false ) ); 13 14 serializer.Serialize( sw , test ); 15 //ここでエラー 16 sw.Close(); 17 18 MessageBox.Show( "保存しました" ); 19 20 21 } 22 23
下記エラーになります。エラーメッセージは
System.InvalidOperationException' の例外が System.Xml.dll で発生しましたが、ユーザー コード内ではハンドルされませんでした
と表示されます。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/02/06 23:17