我有一个具有互斥属性的类。
enum CellType : byte
{ Date, Teams, Value, Text }
class CellCheck
{
public CellType CellType { get; set; }
public float? MinValue { get; set; }
public float? MaxValue { get; set; }
public bool TextCaseSensitive { get; set; }
public string Text { get; set; }
:
}
当CellType为Date或Teams MinValue时,MaxValue,TextCaseSensitive和Text无关。 MinValue和MaxValue仅在CellType为Value时相关。 TextCaseSensitive和Text仅在CellType为Text时才相关。
编写构造函数的最佳方法是什么?现在我正在使用它:
public CellCheck(float fMinValue, float fMaxValue) : this(CellType.Value, fMinValue, fMaxValue, false, null)
{}
public CellCheck(bool bTextCaseSensitive, string strText) : this(CellType.Text, null, null, bTextCaseSensitive, strText)
{}
public CellCheck(CellType Type, float? fMinValue, float ?fMaxValue, bool bTextCaseSensitive, string strText)
{
if (Type == CellType.Value)
{
if (!fMinValue.HasValue)
throw new ArgumentNullException("fMinValue argument in CellCheck constructor is null.");
if (!fMaxValue.HasValue)
throw new ArgumentNullException("fMaxValue argument in CellCheck constructor is null.");
if (fMinValue.Value > fMaxValue.Value)
throw new ArgumentException("fMinValue argument in CellCheck constructor must be less or equal to fMaxValue argument.");
bTextCaseSensitive = false;
strText = null;
}
else
if (Type == CellType.Text)
{
if (strText == null)
throw new ArgumentNullException("strText argument in CellCheck constructor is null.");
fMinValue = null;
fMaxValue = null;
}
else
{
fMinValue = null;
fMaxValue = null;
bTextCaseSensitive = false;
strText = null;
}
CellType = Type;
MinValue = fMinValue;
MaxValue = fMaxValue;
TextCaseSensitive = bTextCaseSensitive;
Text = strText;
}
这被认为是一种很好的编程习惯吗?
答案 0 :(得分:0)
当CellType为Date或Teams MinValue时,MaxValue,TextCaseSensitive和Text无关。 MinValue和MaxValue仅在CellType为Value时相关。 TextCaseSensitive和Text仅在CellType为Text时相关。
对我来说,你需要为每种细胞类型设置一个不同的类,所有类都实现了一个通用的接口:
interface ICellCheck
{
// I'm guessing these classes should check the cells of something,
// but this interface should hold Whatever the different
// CellCheck implementations have is common
bool CheckCell();
}
class DateCellCheck : ICellCheck
{
public bool CheckCell()
{
// implementation here
}
}
class TeamCellCheck : ICellCheck
{
public bool CheckCell()
{
// implementation here
}
}
class ValueCellCheck : ICellCheck
{
public float? MinValue { get; set; }
public float? MaxValue { get; set; }
public bool CheckCell()
{
// implementation here
}
}
class TextCellCheck : ICellCheck
{
public bool TextCaseSensitive { get; set; }
public string Text { get; set; }
public bool CheckCell()
{
// implementation here
}
}
此外,您可能希望将此实现与Factory方法设计模式相结合, 因此,其余代码不需要知道接口的实现细节:
enum CellType : byte
{ Date, Teams, Value, Text }
static class CellCheckFactory
{
ICellCheck Create(CellType cellType)
{
switch(cellType)
{
case CellType.Date:
return new DateCellCheck();
case CellType.Teams:
return new TeamCellCheck();
case CellType.Value:
return new ValueCellCheck();
case CellType.Text:
return new TextCellCheck();
}
}
}