この問題の最善の解決策は何ですか? null が意味のある値であり、デフォルトとして使用できないクラス型のいくつかのオプション パラメータを持つ関数を作成しようとしています。のように、
public void DoSomething(クラス 1 オプション 1、クラス 2 オプション 2、クラス 3 オプション 3) { if (! WasSpecified(optional1)) { optional1 = defaultForOptional1; } if (! WasSpecified(optional2)) { optional2 = defaultForOptional2; } if (! WasSpecified(optional3)) { optional3 = defaultForOptional3; } // ... 実際の作業を行います ... }
Class1 optional1 = null
nullは意味があるので使えません。これらのオプションのパラメーターにはコンパイル時の定数が必要なため、一部のプレースホルダー クラス インスタンスを使用できませんClass1 optional1 = defaultForOptional1
。次のオプションを考え出しました。
- 可能なすべての組み合わせでオーバーロードを提供します。つまり、このメソッドには 8 つのオーバーロードがあります。
- デフォルトを使用するかどうかを示す各オプション パラメータにブール型パラメータを含めます。これにより、署名が乱雑になります。
これに対する巧妙な解決策を思いついた人はいますか?
ありがとう!
編集:のラッパークラスを作成することになったので、繰り返し続ける必要はありませんでしたBoolean HasFoo
。
/// <summary>
/// A wrapper for variables indicating whether or not the variable has
/// been set.
/// </summary>
/// <typeparam name="T"></typeparam>
public struct Setable<T>
{
// According to http://msdn.microsoft.com/en-us/library/aa288208%28v=vs.71%29.aspx,
// "[s]tructs cannot contain explicit parameterless constructors" and "[s]truct
// members are automatically initialized to their default values." That's fine,
// since Boolean defaults to false and usually T will be nullable.
/// <summary>
/// Whether or not the variable was set.
/// </summary>
public Boolean IsSet { get; private set; }
/// <summary>
/// The variable value.
/// </summary>
public T Value { get; private set; }
/// <summary>
/// Converts from Setable to T.
/// </summary>
/// <param name="p_setable"></param>
/// <returns></returns>
public static implicit operator T(Setable<T> p_setable)
{
return p_setable.Value;
}
/// <summary>
/// Converts from T to Setable.
/// </summary>
/// <param name="p_tee"></param>
/// <returns></returns>
public static implicit operator Setable<T>(T p_tee)
{
return new Setable<T>
{
IsSet = true
, Value = p_tee
};
}
}