简体   繁体   中英

ToString() for a class property?

Supposing I have a class "Item", which has three member variables: string name, decimal quantity and string unit. I have got public get/set properties on all three.

Sometimes, I want to display quantity as text along with correct unit, eg. 10m or 100 feet.

My question is, is it possible to have some sort of ToString() function for properties too, so that their text output can be customized?

Thanks,

Saurabh.

What you can do is to make a new (readonly) property returning a formatted version:

public string QuantityAsString
{
    get
    {
        return string.Format("{0} {1}", this.Quantity, this.Unit);
    }
}

It sounds like your object model isn't correctly factored. What you probably want to do is abstract Unit and Quantity into another object and then you can override ToString for that. This has the advantage of keeping dependent values together, and allowing you to implement things such as conversions between units in the future (eg conversion from inchest to feet etc.), eg

public struct Measure
{
    public Measure(string unit, decimal quantity)
    {
        this.Unit = unit;
        this.Quantity = quantity;
    }

    public string Unit { get; private set; }
    public decimal Quantity { get; private set; }

    public override string ToString() 
    { 
        return string.Format("{0} {1}", this.Quantity, this.Unit);
    }
}

public class Item
{
    public string Name { get; set; }
    public Measure Measure { get; set; }

    public override string ToString() 
    { 
        return string.Format("{0}: {1}", this.Name, this.Measure);
    }
}

Note that I made Measure a struct here as it probably has value semantics. If you take this approach you should make it immutable and override Equals/GetHashCode as is appropriate for a struct.

Generally speaking, formatting values to appropriate units is not the responsibility of the Item class. Rather, this should be done by some external class.

If, however, you really want to do formatting inside the class, I'd recommend defining a Unit class with implicit conversion operators to convert to decimal or int s and all the required formatting logic.

我认为从代码质量的角度来看,最好的方法是创建一个用单元包装值并在那里提供.ToString()

You have two options:

  1. Have the ToString() of the parent class automatically append these pieces together into a nice format.
  2. Wrap the properties in classes and provide a ToString() for those classes

You could implement the IFormatable interface to have different ToString's

public class Item : IFormattable
{
    public string Name;
    public decimal Quantity;
    public string Unit;

    public override string ToString(string format, IFormatProvider provider)
    {
        switch(format)
        {
            case "quantity": return Quantity + Unit;
            default: return Name;
        }
    }
}

This can be used like this:

Item item = new Item();
Console.WriteLine(item.ToString());
Console.WriteLine("Quantity: {0:quantity}", item);

A few days ago I implemented the same model. And I made separate classes for Quantity and Unit. It looks like this (it is simplified, in fact there are constructors and overloaded operators):

class Quantity
{
    public decimal Value;
    public UnitOfMeasure Unit;

    public override string ToString() 
    {
        return string.Format("{0} {1}", Value, Unit); 
    }
}

class UnitOfMeasure
{
    public string Name;

    public override string ToString() { return Name; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM