C# ToString() 用于类属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/829190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ToString() for a class property?
提问by virtualmic
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.
假设我有一个“Item”类,它有三个成员变量:字符串名称、十进制数量和字符串单位。我在所有三个上都有公共获取/设置属性。
Sometimes, I want to display quantity as text along with correct unit, eg. 10m or 100 feet.
有时,我想将数量显示为文本以及正确的单位,例如。10m 或 100 英尺。
My question is, is it possible to have some sort of ToString() function for properties too, so that their text output can be customized?
我的问题是,是否也可以为属性提供某种 ToString() 函数,以便可以自定义它们的文本输出?
Thanks,
谢谢,
Saurabh.
索拉布。
采纳答案by Fredrik M?rk
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);
}
}
回答by Jordan Parmer
You have two options:
您有两个选择:
- Have the ToString() of the parent class automatically append these pieces together into a nice format.
- Wrap the properties in classes and provide a ToString() for those classes
- 让父类的 ToString() 自动将这些部分附加到一个很好的格式中。
- 将属性包装在类中并为这些类提供 ToString()
回答by Anton Gogolev
Generally speaking, formatting values to appropriate units is not the responsibility of the Item
class. Rather, this should be done by some external class.
一般来说,将值格式化为适当的单位不是Item
类的责任。相反,这应该由一些外部类来完成。
If, however, you really want to do formatting inside the class, I'd recommend defining a Unit
class with implicit conversion operatorsto convert to decimal
or int
s and all the required formatting logic.
但是,如果您真的想在类内部进行格式化,我建议定义一个Unit
带有隐式转换运算符的类,以将其转换为decimal
or int
s 以及所有必需的格式化逻辑。
回答by Migol
I think the best approach from the code quality point of view is to create class that will wrap value with unit and provide .ToString()
there.
我认为从代码质量的角度来看,最好的方法是创建用单元包装值并.ToString()
在那里提供的类。
回答by Greg Beech
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 (e.g. conversion from inchest to feet etc.), e.g.
听起来您的对象模型没有正确分解。您可能想要做的是抽象Unit
并Quantity
转换为另一个对象,然后您可以覆盖ToString
它。这具有将相关值保持在一起的优点,并允许您在未来实现单位之间的转换(例如从英寸到英尺的转换等),例如
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.
请注意,我在Measure
这里创建了一个结构体,因为它可能具有值语义。如果您采用这种方法,您应该使其不可变并覆盖适合结构的 Equals/GetHashCode。
回答by Arjan Einbu
You could implement the IFormatable interface to have different ToString's
您可以实现 IFormatable 接口以具有不同的 ToString
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);
回答by Dmitrii Lobanov
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; }
}