Answer the question
In order to leave comments, you need to log in
How to pass a class to the parameters in a c# method?
I want to pass a class in the ObjectToXml parameter for further use in the XmlSerializer,
but this is impossible. How can this problem be solved?
ObjectToXml(resp, ResponseZZZ);
[XmlRoot(ElementName = "response")]
public class ResponseZZZ
{
[XmlElement(ElementName = "txn_id")]
public string txn_id { get; set; }
[XmlElement(ElementName = "result")]
public string Result { get; set; }
[XmlElement(ElementName = "comment")]
public string Comment { get; set; }
}
public static XmlDocument ObjectToXml(Object obj, Class MyClass) {// Нельзя передавать Class
XmlDocument xml = new XmlDocument();
XmlSerializer formatter = new XmlSerializer(typeof(ResponseZZZ));
using (MemoryStream memStm = new MemoryStream())
{
formatter.Serialize(memStm, obj);
memStm.Position = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (var xtr = XmlReader.Create(memStm, settings))
{
xml = new XmlDocument();
xml.Load(xtr);
}
}
return xml;
}
Answer the question
In order to leave comments, you need to log in
class Program
{
static void Main(string[] args)
{
ObjectToXml(new object(), new ResponseZZZ());
Console.ReadLine();
}
public static XmlDocument ObjectToXml<SerializationType>(Object obj, SerializationType MyClass) where SerializationType : class, new()
{
XmlDocument xml = new XmlDocument();
XmlSerializer formatter = new XmlSerializer(typeof(SerializationType));
using (MemoryStream memStm = new MemoryStream())
{
formatter.Serialize(memStm, obj);
memStm.Position = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (var xtr = XmlReader.Create(memStm, settings))
{
xml = new XmlDocument();
xml.Load(xtr);
}
}
return xml;
}
}
[XmlRoot(ElementName = "response")]
public class ResponseZZZ
{
[XmlElement(ElementName = "txn_id")]
public string txn_id { get; set; }
[XmlElement(ElementName = "result")]
public string Result { get; set; }
[XmlElement(ElementName = "comment")]
public string Comment { get; set; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question