使用此示例代码:
public class Product
{
private Boolean _active;
public Boolean active
{
get
{
return _active;
}
set
{
_active = value;
}
}
}
Product p = new Product();
p.active = true;
如何覆盖ToString()
方法,以便我可以使用它:
MessageBox.Show(p.active.ToString());
答案 0 :(得分:3)
对于它的价值,您可以使用扩展方法:
toImmutable()
这是因为你的拼写错误,internal
而不是public static string toString(this bool b)
{
return b ? "Si" : "No";
}
MessageBox.Show(p.active.toString());
。
您无法在不更改方法的情况下更改方法的返回值。 Boolean.ToString
会返回toString
或ToString
,但没有任何内容可以更改(除了Microsoft)。
但当然你也可以写:
"True"
答案 1 :(得分:1)
我不确定你可以像你想要的那样覆盖它。也许您可以使用三元运算符来进行小评估,例如
MessageBox.Show(p.active ? 'Yes' : 'No');
答案 2 :(得分:-1)
为什么要覆盖变量的ToString而不是对象的ToString?你能解释一下你的情景吗?而不是创建一个扩展方法,当您在变量上调用ToString时将所有“bool”视为“是”或“否”,我建议您使用对象的ToString或使用属性来显示您的信息
class Program
{
static void Main(string[] args)
{
Product p = new Product();
Console.WriteLine(p);
Console.ReadLine();
}
}
public class Product
{
private Boolean _active;
public Boolean active
{
get
{
return _active;
}
set
{
_active = value;
}
}
public override string ToString()
{
return active ? "Yes" : "No";
}
}
如果您想使用属性,可以使用此处描述的方法创建扩展方法https://stackoverflow.com/a/672212/819153
class Program
{
static void Main(string[] args)
{
Product p = new Product();
var attValue = Helper.ToStringProperty(p, prod => prod.active);
Console.WriteLine(attValue);
Console.ReadLine();
}
}
public class Product
{
private Boolean _active;
[Display(Name = "Super Active")]
public Boolean active
{
get
{
return _active;
}
set
{
_active = value;
}
}
}
public class Helper
{
public static string ToStringProperty<TSource, TProperty>(TSource source,
Expression<Func<TSource, TProperty>> propertyLambda)
{
Type type = typeof(TSource);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
var output = source.ToString();
var attribute = propInfo.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>().FirstOrDefault();
return attribute != null ? attribute.Name : output;
}
}