I have an extension method for deserialization of an XDocument.
I use CarConfiguration as variable in this method, but I have another class configurations:
public static CarConfiguration Deserialize(this XDocument xdoc)
{
XmlSerializer serializer = new XmlSerializer(typeof(CarConfiguration));
using (StringReader reader = new StringReader(xdoc.ToString()))
{
CarConfiguration cfg = (CarConfiguration) serializer.Deserialize(reader);
return cfg;
}
}
class CarConfiguration
{
//car
}
class BikeConfiguration
{
//bike
}
So, there are 2 questions here:
Can I use class name as parameter for this method? Something like this:
static CarConfiguration Deserialize(this XDocument xdoc, class classname) {
var serializer = new XmlSerializer(typeof(classname));
Can I make this method generic for all required types(CarConfiguration, BikeConfiguration etc.)? I mean for example dependency of return type on input class:
static <classname> Deserialize(this XDocument xdoc, class classname) {
The key word in your question is generic, so yes you can do this by utilising C# generics. For example:
public static T Deserialize<T>(this XDocument xdoc)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xdoc.ToString()))
{
T cfg = (T) serializer.Deserialize(reader);
return cfg;
}
}
And now you call it like this:
CarConfiguration x = xmlDocument.Deserialize<CarConfiguration>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With