ObsoleteAttribute和Generic Methods

时间:2014-01-26 17:01:51

标签: c# generics obsolete generic-method

我正在为我的Serializer类添加一个新的通用Serialize方法。旧的必须过时。

[XmlRoot("a")]
public class A
{
    [XmlElement("field")]
    public string Field;
}

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        a.Field = "filed value";

        Console.WriteLine(Serialize(a));//this calls generic version !?
        Console.WriteLine();
        Console.WriteLine(Serialize(null));//ok
        Console.WriteLine();
        Console.WriteLine(Serialize<A>(a));//ok, we explicitly called generic version
    }

    [Obsolete("Use Serialize<T> instead")]
    public static string Serialize(Object pObject)
    {
        return "You have called old Serialize method";
    }

    public static string Serialize<T>(T value)
    {
        return "You have called new Serialize<T> method";
    }
}

预期结果应为:

You have called old Serialize method

You have called old Serialize method

You have called new Serialize<T> method

但结果是:

You have called new Serialize<T> method

You have called old Serialize method

You have called new Serialize<T> method

那么为什么Serialize(a)调用泛型版本?通用的废弃方法是否存在错误?

1 个答案:

答案 0 :(得分:1)

如果您将a投放到object,您将获得预期的结果

Console.WriteLine(Serialize((object)a))