【发布时间】:2012-05-23 20:32:45
【问题描述】:
这个问题的最佳解决方案是什么?我正在尝试创建一个函数,该函数具有多个类类型的可选参数,其中 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
};
}
}
【问题讨论】:
-
重载不会让你传递文字空常量。 (只是风格问题。)
-
你到底想在这里完成什么?