文字列入力を処理する関数があります。
public string Foo(string text)
{
// do stuff with text and
// return processed string
}
GUIDを次のような文字列に変換していた多くの場所からこれを呼び出していました:
string returnValue = Foo(bar.ToString());
私が実際に望んでいたのは、文字列に変換できる任意のオブジェクト型を入力として受け入れることでした。そこで、関数を次のように変更してみました。
public string Foo(IFormattable text)
{
var textAsString = text.ToString();
// do stuff with textAsString
// and return processed string
}
これは、すべての呼び出しがより簡単であることを意味します。
string returnValue = Foo(bar);
.ToString メソッドを持つすべてのオブジェクト タイプで機能します。文字列を除く:)
関数に文字列を渡そうとすると、次のコンパイル エラーが発生します。
Argument type 'string' is not assignable to parameter type 'System.IFormattable'
String には ToString() メソッドがあるため、これは非常に奇妙に思えます。
なぜこれが機能しないのですか?