あなたの例では、構文(つまり、「使いやすさ」)が唯一の利点だと思います。ただし、たとえば LINQ メソッドの動作は異なります。メソッドはthis
を返さず、新しいインスタンスを返します。これは明らかにパフォーマンス ヒットですが、クラスを不変にすることができます。これは、コードについて考えるときに非常に役立ちます。そのようなクラスで並列計算を促進できます。
編集(例):その場合、あなたCoffee
は次のようになります(ただし、ここで流暢な構文を使用することはあまり意味がないため、良い例ではないかもしれませんが、新しいインスタンスは言うまでもありません)
public class Coffee
{
private bool _cream;
private int _ounces;
// I really don't like this kind of instantiation,
// but I kept it there and made static to make it work.
public static Coffee Make { get new Coffee(); }
public Coffee WithCream()
{
return new Coffee
{
_cream = true,
_ounces = this._ounces
}
}
public Coffee WithOuncesToServe(int ounces)
{
return new Coffee
{
_cream = this._cream,
_ounces = ounces
};
}
もちろん、このような単純なクラスの場合は、コンストラクターをパラメーターとともに使用することをお勧めします。
public Coffee(int ounces, bool cream)
逆の例として、Dictionary
新しいインスタンスを作成せずにアイテムを流暢に追加するための一連の便利な拡張機能を覚えています。何かのようなもの:
public static IDictionary<K, V> AddConditionally(
this IDictionary<K, V> source,
K key, V value)
{
// Real-life implementation would contain more checks etc.
if(!source.ContainsKey(key))
source.Add(key, value);
return source;
}
たとえば、辞書に初期データを入力するために使用できるもの
var dict = new Dictionary<int, int>()
.AddConditionally(0,1)
.AddConditionally(1,1)
.AddConditionally(2,1)
.AddConditionally(3,1);