【发布时间】:2012-12-19 22:49:38
【问题描述】:
我需要能够调用一个方法并传入一个未知类型的对象
但随后调用正确的重载。我还需要一个接受的默认实现
object 作为其参数类型。我看到的是默认重载是唯一被使用过的。
这是我想要做的事情的要点:
class Formatter
{
private object Value;
public Formatter(object val){
Value = val;
}
public override string ToString()
{
return Format(Value);
}
private string Format(object value)
{
return value.ToString();
}
private string Format(DateTime value)
{
return value.ToString("yyyyMMdd");
}
}
好的,到目前为止一切顺利。现在我希望能够做到这一点:
public static class FancyStringBuilder()
{
public static string BuildTheString()
{
var stringFormatter = new Formatter("hello world");
var dateFormatter = new Formatter(DateTime.Now);
return String.Format("{0} {1}", stringFormatter, dateFormatter);
}
}
FancyStringBuilder.BuildTheString() 的结果是"hello world 2012-12-21 00:00:00.000",而我期望的是"hello world 20121221"
问题是没有调用接受DateTime 的重载,而是默认为接受object 的重载。 如何在不使用混乱的 switch 语句的情况下调用正确的方法?
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c#-4.0 overloading