How to add XmlInclude attribute dynamically

后端 未结 4 1712
青春惊慌失措
青春惊慌失措 2020-11-27 05:20

I have the following classes

[XmlRoot]
public class AList
{
   public List ListOfBs {get; set;}
}

public class B
{
   public string BaseProperty {g         


        
4条回答
  •  时光说笑
    2020-11-27 05:30

    Building on Marc's first answer (I only have to read, so I don't need to prevent the weird output), I use a more dynamic/generic type-array to account for unknown types, inspired by this codeproject.

        public static XmlSerializer GetSerializer()
        {
            var lListOfBs = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies()
                               from lType in lAssembly.GetTypes()
                               where typeof(B).IsAssignableFrom(lType)
                               select lType).ToArray();
            return new XmlSerializer(typeof(AList), lListOfBs);
        }
    

    (One could probably make it more efficient, e.g. using a static or read-only type-array in stead of a local variable. That would avoid repeatedly using Reflection. But I don't know enough about when assemblies get loaded and classes and properties get initialized, to know if that would get you into trouble. My usage is not that much, to take the time to investigate this all, so I just use the same Reflection multiple times.)

提交回复
热议问题