如何重写 ToString() 方法?

huangapple go评论73阅读模式
英文:

How to override ToString() method?

问题

In the following code (edited for brevity), I want to override the behaviour of the .ToString() method. Using "override" only tells me that "no suitable method was found to override". If I use "new", it compiles and builds OK, but the code never uses the new ToString(). It just continues to use the native .NET .ToString() method.

Any idea what's wrong?

public class Form_Processor {

    public Form_Processor() {

        SqlDataReader rs;
		
		//SNIP database query

        while (rs.Read()) {

                result = rs["ReportDateTime"].ToString("dd");
		}
		
		rs.Close();
		
	}
	
    // **********************************************************
    
    public new string ToString(string strFormat) {

        if (strFormat != null) {
            return "OK";
        }

        return null;
		
    }

}

(Note: The code portion has been translated, as requested.)

英文:

In the following code (edited for brevity), I want to override the behaviour of the .ToString() method. Using "override" only tells me that "no suitable method was found to override". If I use "new", it compiles and builds OK, but the code never uses the new ToString(). It just continues to use the native .NET .ToString() method.

Any idea what's wrong?

public class Form_Processor {

    public Form_Processor() {

        SqlDataReader rs;
		
		//SNIP database query

        while (rs.Read()) {

                result = rs["ReportDateTime"].ToString("dd");
		}
		
		rs.Close();
		
	}
	
    // **********************************************************
    
    public new string ToString(string strFormat) {

        if (strFormat != null) {
            return "OK";
        }

        return null;
		
    }

}

答案1

得分: 2

ToString()ToString(string strFormat) 是两个不同的方法。ToString(string) 是一个重载而不是 ToString() 的覆盖。

错误消息 "no suitable method was found to override" 是正确的。Form_Processor 隐式地继承自 Object,并且有一个 Object.ToString() 方法,但在 Object 上没有 ToString(string) 的重载。

要覆盖 ToString(),请使用 public override string ToString() ...

英文:

ToString() and ToString(string strFormat) are two different methods. ToString(string) is an overload and not an override of ToString().

The error message "no suitable method was found to override" is correct. Form_Processor is implicitly derived from Object and there is an Object.ToString() method but there is no ToString(string) overload on Object.

To override ToString() use public override string ToString() ....

答案2

得分: 2

I suspect you're trying to apply 自定义字符串格式化. To do that, try implementing IFormattable.

void Main()
{
    object foo = new Foo();
    Console.WriteLine($"{foo:dd}"); // 输出: OK
    Console.WriteLine(((IFormattable)foo).ToString("dd", null)); // 输出: OK
}

public class Foo : IFormattable
{
    public string ToString(string? format, IFormatProvider? formatProvider)
    {
        if (format != null)
        {
            return "OK";
        }

        return "Not OK";
    }
}

(Note: The code has been translated, and the link remains in its original form.)

英文:

Reading between the lines, I suspect you're trying to apply Custom String Formatting. To do that, try implementing IFormattable.

void Main()
{
    object foo = new Foo();
    Console.WriteLine($"{foo:dd}"); // output: OK
    Console.WriteLine(((IFormattable)foo).ToString("dd", null)); // output: OK
}


public class Foo : IFormattable
{
    public string ToString(string? format, IFormatProvider? formatProvider)
    {
        if (format != null)
        {
            return "OK";
        }

        return "Not OK";
    }
}

答案3

得分: 1

以下是您要翻译的内容:

This:

    rs["ReportDateTime"].ToString("dd")

Has nothing to do with this:

    public new string ToString(string strFormat) {

You're trying to override `ToString(string strFormat)` on your `Form_Processor` class.  Which, in the absense of an explicit inherited class, inherits from `Object`.  Which [has no such method](https://learn.microsoft.com/en-us/dotnet/api/system.object).

According to [the documentation](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader), `rs` here is of type `Object`.  Your class *inherits* from `Object`, but `Object` itself has nothing to do with your class.

If your goal is to apply a format string for this operation:

    rs["ReportDateTime"].ToString("dd")

Then overall it sounds like overriding was simply the wrong approach and ended up confusing you.  If the goal is for this class to have a method which can be used to format values within this class, why not just... write a method for that?  For example:

    public string FormatString(object obj, string strFormat) {
        // your "ToString" logic for "obj"
    }

And to use it:

    FormatString(rs["ReportDateTime"], "dd")

You can override `ToString()` (or add a `ToString(string strFormat)`) in your class which would be used when calling that method *on an instance of your class*.  But that's simply not what the code is doing.
英文:

This:

rs["ReportDateTime"].ToString("dd")

Has nothing to do with this:

public new string ToString(string strFormat) {

You're trying to override ToString(string strFormat) on your Form_Processor class. Which, in the absense of an explicit inherited class, inherits from Object. Which has no such method.

According to the documentation, rs here is of type Object. Your class inherits from Object, but Object itself has nothing to do with your class.

If your goal is to apply a format string for this operation:

rs["ReportDateTime"].ToString("dd")

Then overall it sounds like overriding was simply the wrong approach and ended up confusing you. If the goal is for this class to have a method which can be used to format values within this class, why not just... write a method for that? For example:

public string FormatString(object obj, string strFormat) {
    // your "ToString" logic for "obj"
}

And to use it:

FormatString(rs["ReportDateTime"], "dd")

You can override ToString() (or add a ToString(string strFormat)) in your class which would be used when calling that method on an instance of your class. But that's simply not what the code is doing.

huangapple
  • 本文由 发表于 2023年6月15日 00:02:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定