XmlSerializer requires XmlInclude for a public method with a common constraint if the type is in a different assembly AND requires this type to be consistent!

Consider the following. You have a class that you want to serialize using the XmlSerializer, which has a publicly accessible general method with a constraint type, where the type is in a different assembly:

using BarStuff;

namespace FooStuff {
  public class Foo {
    ...
    public T GetBar<TBar, T>( string key ) where TBar : Bar<T> {
      ...
    }
  }
}

You would not expect the XmlSerializer to even refer to methods, and this is usually not the case. The following both work fine:

//private, serializer doesn't care about it
private T GetBar<TBar, T>( string key ) where TBar : Bar<T> {
  ...
}

//no generic type constraint, serializer also doesn't care about it
public Bar GetBar( string key ) {
  ...
}   

In addition, if the Bar type is in the same assembly as Foo, the serializer will also be completely happy.

, Bar , , , , Bar, . , XmlInclude:

[XmlInclude(typeof(Bar))]
public class Foo {
  public T GetBar<TBar, T>( string key ) where TBar : Bar<T> {
    ...
  }
}

, Bar , , , -, , , , , ..!

, : XmlSerializer InvalidOperationException ,

: Microsoft

+3
1

:

:

namespace BarStuff {
  //the serializer is perfectly happy with me
  public class DummyBar{}

  //the serializer doesn't like me
  public class Bar{
  ...
  }

  ...
}

using BarStuff;
namespace FooStuff {
  [XmlInclude(typeof(DummyBar))]
  public class Foo {
    public T GetBar<TBar, T>( string key ) where TBar : Bar<T> {
      ...
    }
  }
+2

Source: https://habr.com/ru/post/1764812/


All Articles