简体   繁体   English

在C#中使用相同的方法序列化不同的类

[英]Serialize different classes with same Method in c#

I have different classes that are serializeable. 我有可序列化的不同类。

I have a method to do so which looks like this: 我有一个这样做的方法,如下所示:

public void Serialize(List<ClassName1> CT, string Address)
{
    ...
    XmlSerializer serializer = new XmlSerializer(typeof(List<ClassName1>));
    ...
}

In order to serialize ClassName1 i can use this function, but i cannto use it for a second class named ClassName2. 为了序列化ClassName1,我可以使用此函数,但是我不能将其用于名为ClassName2的第二个类。 THe classes are different, but both are serializeable. 类是不同的,但是两者都是可序列化的。

I could now copy and paste the Method and just change the classes but i feel that this is stupid, since the only difference with the methods are the names. 我现在可以复制并粘贴Method并只更改类,但是我觉得这很愚蠢,因为与方法唯一的区别是名称。

I tried to do it like this: 我试图这样做:

public void Serialize(List<object> CT, string Address)
{
    ...
    XmlSerializer serializer = new XmlSerializer(typeof(List<object>));
    ...
}

Since i thought everything is an "object" in c# but when i use it i get the "cannot convert" error. 由于我以为一切都是C#中的“对象”,但是当我使用它时,出现“无法转换”错误。

xml.Serialize(listNumber, Address);

I have the feeling this can be solved with generics, but i never worked with generic of any kind so i have absolutely no idea if and how it should work. 我感觉可以使用泛型来解决,但是我从未使用过任何泛型,因此我完全不知道它是否以及如何工作。

This is an ideal usage of generics: 这是泛型的理想用法:

public void Serialize<T>(List<T> CT, string Address)
{
    ...
    XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
    ...
}

and in most cases you won't even have to change the calling code - the compiler will infer the generic type argument automatically. 在大多数情况下,您甚至不必更改调用代码-编译器会自动推断出泛型类型参数。

Since the Serialize method of the XmlSerializer has an object parameter for the object to serialize, just do the same. 由于XmlSerializerSerialize方法具有要序列化的对象的object参数,因此请执行相同的操作。

public void Serialize(object obj, string Address)
{
    ...
    XmlSerializer serializer = new XmlSerializer(obj.GetType());
    ...
}

There seems to be no advantage in using generics unless your methods does other things with the list. 除非您的方法对列表进行其他操作,否则使用泛型似乎没有任何优势。 In this case use Marc Gravell's approach. 在这种情况下,请使用Marc Gravell的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM