扩展方法无法实现 ToString

Extension method can't implement ToString

我正在尝试使用扩展方法在没有它的 class 中实现 ToString()。如果我将方法声明更改为 ToString2(),它工作正常,但是当我尝试使用 .ToString 时它失败了。为什么 ToString2() 有效,但 ToString() 无效?

错误:

System.NullReferenceException: Object reference not set to an instance of an object.

这是我的方法实现:

namespace LeankitExtensions
{
    public static class CardViewExt
    {
        public static string ToString(this CardView c)
        {
            if (c == null)
                return "null card";

            return String.Format("-------\nexternal id: {0} \ntitle: {1}\n-------",c.ExternalCardID,c.Title);
        }
    }
}

调用方法:

CardView cv = new CardView(){ExternalCardID="22";Title="Hi"};
Console.WriteLine(cv.ToString());

因为 ToString() 是 class 对象的一个​​方法,如果您想使用方法名称 ToString(),您需要重写它的基础 class 版本。您将无法创建一个名为 ToString() 的扩展方法,因为基础 class 对象中已经存在一个扩展方法。如果您想将此作为扩展方法,请将其称为 CardViewToString()

C# 中的每个 class 默认情况下都继承自对象 class,它有一些我们可以覆盖的方法,其中三个是 ToString()、Equals() 和 GetHashCode()。

现在您的代码的问题在于,您没有覆盖 CardView class 中的 ToString() 方法,而是创建了扩展方法。你应该做的是覆盖 CardView class 中的 ToString() 方法,正如我在下面的代码中所示。

    public override string ToString()
    {

        //if (this == null) -- Not needed because the ToString() method will only be available once the class is instantiated.
        //    return "null card";

        return String.Format("-------\nexternal id: {0} \ntitle: {1}\n-------", this.ExternalCardID, this.Title);
    }

但是,如果 CardView class 在某些您无法编辑的 DLL 中,我建议您创建一个具有其他名称的扩展方法,如下所示。

public static class CardViewExt
{
    public static string ToStringFormatted(this CardView c)
    {
        if (c == null)
            return "null card";

        return String.Format("-------\nexternal id: {0} \ntitle: {1}\n-------", c.ExternalCardID, c.Title);
    }
}