C# 如何用扩展方法重写Object.ToString()方法?
该方法用于将任何对象转换为可读文本字符串。但如果对象为null,则抛出C# 如何用扩展方法重写Object.ToString()方法?,c#,.net,C#,.net,该方法用于将任何对象转换为可读文本字符串。但如果对象为null,则抛出NullReferenceError。所以我想用扩展方法覆盖这个ToString()方法,比如: public static class StringExt { public string ToString(this object str) { if (str == null) return System.Convert.ToString(str);
NullReferenceError
。所以我想用扩展方法覆盖这个ToString()
方法,比如:
public static class StringExt
{
public string ToString(this object str)
{
if (str == null)
return System.Convert.ToString(str);
return str.ToString();
}
}
但这似乎永远不会覆盖对象
类的ToString()
Myclass cls;
//doing something on the other hand.
cls.ToString();
此处
cls.ToString()
始终使用Object.ToString()
方法。有没有办法做到这一点?扩展方法不能故意取代实例方法
您需要使用不同的名称。我不赞成使用不同的名称,因为这很容易被忽略。有没有其他方法可以覆盖任何类型对象的implemantation。@Jodha:您可以重写IL。问题不在于您总是试图取消对空对象的引用,因此总是抛出异常吗?看起来你在试图解决无法解决的问题。。。