【发布时间】:2014-12-20 22:27:16
【问题描述】:
我有一个类,我想轻松地将其写入字符串(例如,用于记录目的)。我可以使用隐式运算符将对象隐式转换为字符串而不是覆盖 ToString 方法吗?
例如,我有一个带有 Name 和 Age 的 Person 类:
public class Person
{
public string Name { get; set; }
public int Age { get; set;}
}
我可以覆盖 ToString:
public override string ToString()
{
return String.Format("Name: {0}, Age: {1}", this.Name, this.Age);
}
或者我可以使用隐式运算符:
public static implicit operator string(Person p)
{
return String.Format("Name: {0}, Age: {1}", p.Name, p.Age);
}
现在,当将此对象传递给需要字符串的方法时,而不是
Log(Person.ToString());
我可以打电话
Log(Person);
我什至可以在隐式转换中调用重写的 ToString
public static implicit operator string(Person p)
{
return p.ToString();
}
这是对隐式运算符转换为字符串的不好使用吗?
需要此功能时的最佳做法是什么?
我怀疑仅重载 ToString 将是最佳实践答案,如果是这样,我有几个问题:
- 我什么时候会使用隐式转换为字符串?
- 使用隐式强制转换为字符串的最佳实践示例是什么?
【问题讨论】:
标签: c# operator-overloading implicit-conversion