C# - 接受任何类型参数的方法(重用现有方法)

时间:2012-02-21 21:04:21

标签: c# c#-4.0

我有一个方法serializetoxml,它接受​​obj1类型的对象作为其参数:

class Program
{
    static void Main(string[] args)
    {
        obj1 myobj = new obj1();
        serializetoxml(myobj);    
    }
}

public class obj1
{
    public string a { get; set; }
    public int b { get; set; }
    public bool c { get; set; }
}

public static void serializetoxml(obj1 myobj)
{
    XmlSerializer myserializer = new XmlSerializer(typeof(obj1));
    TextWriter mywriter = new StreamWriter("C:\\my.xml");
    myserializer.Serialize(mywriter, myobj);
    mywriter.Close();
}

现在我有一个类obj2,我希望将其作为参数传递

public class obj2
{
    public int a { get; set; }
    public bool b { get; set; }
    public List<string> c { get; set; }
}

如何重用serializetoxml方法以便能够接受其他类型的参数,这样我就不会再次编写相同的方法并将typeof更改为obj2

obj2 myobj = new obj2();
serializetoxml(myobj);

6 个答案:

答案 0 :(得分:8)

添加类型参数:

public static void serializetoxml<T>(T myobj)
{
    XmlSerializer myserializer = new XmlSerializer(typeof(T));
    TextWriter mywriter = new StreamWriter("C:\\my.xml");
    myserializer.Serialize(mywriter, myobj);
    mywriter.Close();
}

然后你会像:

一样使用它
serializetoxml<obj2>(myobj);

serializetoxml<obj1>(myobj);

借助类型参数推断的神奇之处,您可以完全省略类型参数(但如果您想将其保留在那里则可以):

serializetoxml(myobj);

答案 1 :(得分:7)

尝试以下

public static void serializetoxml(object myobj) {
    XmlSerializer myserializer = new XmlSerializer(myobj.GetType());
    TextWriter mywriter = new StreamWriter("C:\\my.xml");
    myserializer.Serialize(mywriter, myobj);
    mywriter.Close();
}

答案 2 :(得分:1)

将方法移动到静态类,并将其设为extension method,如下所示:

internal static class Extensions {
    public static void SerializeToXml<T>(this T myobj)
        {
            XmlSerializer myserializer = new XmlSerializer(typeof(T));
            TextWriter mywriter = new StreamWriter("C:\\my.xml");
            myserializer.Serialize(mywriter, myobj);
            mywriter.Close();
        }
}

您现在可以像使用实例方法一样使用它。您需要将Extensions类放入同一名称空间,或为其添加using指令。

答案 3 :(得分:1)

两个选项:

  • 泛型:Serialize<T>(T obj)typeof(T)
  • 对象:Serialize(object obj)obj.GetType()

我实际上更喜欢基于苦涩经历的序列化的第二个,但两者都是有效的。

答案 4 :(得分:1)

public static void serializetoxml(object myobj)
{
    XmlSerializer myserializer = new XmlSerializer(obj1.GetType());
    TextWriter mywriter = new StreamWriter("C:\\my.xml");
    myserializer.Serialize(mywriter, myobj);
    mywriter.Close();
}

答案 5 :(得分:0)

真的没问题。只需使序列化方法适用于泛型类型。 请参阅Stack Overflow问题 Using generics with XmlSerializer