这个问题的最佳解决方案是什么?我正在尝试创建一个函数,该函数具有多个类类型的可选参数,其中 null 是一个有意义的值,不能用作默认值。如中,
public void DoSomething(Class1 optional1, Class2 optional2, Class3 optional3) { 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
};
}
}