How to pass variables to overridden toString() method?

和自甴很熟 提交于 2019-12-04 04:20:16

问题


Is it possible to pass in a bool variable into an overridden toString() method, so it can conditionally print the object in different formats?


回答1:


You can define overload method of ToString().

public string ToString(bool status){
  //
}



回答2:


The typical pattern for parametrized ToString() is to declare an overload with a string parameter.

Example:

class Foo
{
    public string ToString(string format)
    {
        //change behavior based on format
    }
}

For a framework example see Guid.ToString




回答3:


If you are talking about your own class, you could do the following:

public class MyClass
{
    public bool Flag { get; set; }

    public MyClass()
    {
        Flag = false;
    }

    public override string ToString()
    {
        if (Flag)
        {
            return "Ok";
        }
        else
        {
            return "Bad";
        }
    }
}

And use it

MyClass c = new MyClass();
Console.WriteLine(c); //Bad
c.Flag = true;
Console.WriteLine(c); //Ok
Console.ReadLine();

Your Flag could be some private field and change its value, depending on some inner conditions. It's all up to you.




回答4:


No. An overriding method must have the same signature as the method it's overriding. This means that it can't have any more parameters, since that would change the signature. I would just make a new method for the other format you want.



来源:https://stackoverflow.com/questions/12505472/how-to-pass-variables-to-overridden-tostring-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!