なぜメソッドをオーバーロードしないのですか?
using System;
namespace test {
static class Formatter {
const string DateFormat = "MMM dd yyyy";
const string NumberFormat = "0.0";
public static string Format(double d) {
return d.ToString(NumberFormat);
}
public static string Format(DateTime d) {
return d.ToString(DateFormat);
}
// most generic method
public static string Format(object o) {
return o.ToString();
}
}
class Program {
public static void Main() {
Console.WriteLine(Formatter.Format(2.0d));
Console.WriteLine(Formatter.Format(DateTime.Now));
// an integer => no specific function defined => pick the
// most generic overload (object)
Console.WriteLine(Formatter.Format(4));
}
}
}
注:あなたはタイプを比較する必要がある場合、あなたは
if (typeof(int) == t){
// ...
}
を使用する必要がありますし、タイプ名に比較を行う(あるいは、少なくとも、あなたがそれを行う場合は、完全にをチェックしませんが修飾された型名、すなわち名前空間を含む)。
EDIT
辞書タイプ - >機能を使用して、アカウントにアロンさんのコメントを取る代替ソリューション、この第二の溶液で
using System;
using System.Collections.Generic;
namespace test {
public class Formatter {
delegate string FormatFunction(object o);
private string FormatDouble(object o) {
double d = (double)o;
return d.ToString("0.0");
}
private string FormatDateTime(object o) {
DateTime d = (DateTime)o;
return d.ToString("MMM dd yyyy");
}
// map types to format function
private Dictionary<Type, FormatFunction> _formatters = new Dictionary<Type, FormatFunction>();
public Formatter() {
_formatters.Add(typeof(double), FormatDouble);
_formatters.Add(typeof(DateTime), FormatDateTime);
}
public string Format(object o) {
Type t = o.GetType();
if (_formatters.ContainsKey(t)){
return _formatters[t](o);
} else {
return o.ToString();
}
}
}
class Program {
public static void Main() {
Formatter f = new Formatter();
Console.WriteLine(f.Format(2.0d));
Console.WriteLine(f.Format(DateTime.Now));
Console.WriteLine(f.Format(4));
}
}
}
を、あなたはただ持っている場合でも、正しい機能を取得オブジェクトへの参照(私は可能ならば最初の解決策を使用します)。
フォーマットをCurrentCultureに設定してフォーマットを処理することはできますか? – tvanfosson