什么是解决此问题的最佳方案?我正在尝试创建一个函数,该函数具有多个可选参数,这些可选参数是类类型,其中 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; }我不能使用
// ... do the actual work ... }
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
};
}
}