我認爲你已經結束了複雜的事情,最終會創建太多的類。
我認爲問題不在於構建字符串,而在於如何爲.net調用方提供一個很好的接口。正因爲有許多可能的參數並不意味着你需要爲他們創造了大量的課程,至少在每個參數中可能的變化都不是很複雜的,也就是說,如果值是有還是沒有的話,並且有可選單位。然後你陷入這個混亂的需要知道命令的部分命令需要的命令等等。
也許我會爲命令的可能參數創建一個類,讓一個調用者設置它們的任何一個像這樣,並且該類負責在一個大(醜陋的?)字符串連接中生成字符串。
例如,我會從這樣的事情開始,並且隨着你走,我會根據命令的不同部分的相似性重新添加一些方法來重構字符串連接。
class CommandArgs
{
private double? _Position_x = null;
private double? _Position_y = null;
private String _Position_units = null;
private double? _Width = null;
private String _Width_units = null;
private double? _Height = null;
private String _Height_units = null;
// maybe there's a better tuple-like type for this.
public double[] Position
{
set
{
if (value.length != 2) throw new ArgumentException("argh!");
_Position_x = value[0];
_Position_y = value[1];
}
}
public string Position_Units
{
set
{
_Position_Units = value;
}
}
public double Width
set
{
_Width = value;
}
}
public double Height
set
{
_Height = value;
}
}
public string Width_Units
set
{
_Width = value;
}
}
public string Height_Units
set
{
_Height = value;
}
}
// ....
public override string ToString()
{
return
(_Position_x != null ? string.Format(" Position ({0},{1})",_Position_x, _Position_y) : "")
+ (_Height != null ? string.Format(" Height {0}")
+ (_Height_Units != null ? string.Format(" Units {0}", _Height_Units) : "")
+ (_Width != null ? string.Format(" Width {0}")
+ (_Width_Units != null ? string.Format(" Units {0}", _Width_Units) : "")
// ...
;
}
}
如果你喜歡你可能喜歡做方法而不是屬性,所以你可以同時設置值和單位。
我可能會重構與下面的方法立刻道:
private string FormatUnits(string units)
{
return units == null ? "" : string.Format(" Units {0}", units);
}
private string FormatSingleValueArgument(string argName, object argValue, string units)
{
if (argValue == null) return "";
return string.Format(" {0} {1}", argName, argValue) + FormatUnits(units);
}
使得該toString()方法是這樣的:
return
(_Position_x != null ? string.Format(" Position ({0},{1})",_Position_x, _Position_y) : "")
+ FormatSingleValueArgument("Height", _Height, _Height_Units)
+ FormatSingleValueArgument("Width", _Width, _Width_Units)
// ...
;
那麼也許做位置樣的參數類似的方法,如果有幾個。
正試圖避免必須做一堆if語句和空檢查,你給的例子將爲這種情況工作,但它仍然會與我已經包裝的其他一些陳述非常複雜。 – 2008-12-17 02:42:15