How to pass variables to overridden toString() method?

前端 未结 4 1780
孤独总比滥情好
孤独总比滥情好 2021-01-21 08:43

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

4条回答
  •  囚心锁ツ
    2021-01-21 09:32

    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.

提交回复
热议问题