我怎样才能将这些代码重构为一种方法或什么?
if (!string.IsNullOrEmpty(_gridModel.Header))
_gridModel.Header += ",";
if (item != null)
_gridModel.Header += item.Header;
if (!string.IsNullOrEmpty(_gridModel.Width))
_gridModel.Width += ",";
if (item != null)
_gridModel.Width += item.Width;
if (!string.IsNullOrEmpty(_gridModel.Align))
_gridModel.Align += ",";
if (item != null)
_gridModel.Align += item.Align;
if (!string.IsNullOrEmpty(_gridModel.Filter))
_gridModel.Filter += ",";
if (item != null)
_gridModel.Filter += item.Filter;
if (!string.IsNullOrEmpty(_gridModel.Type))
_gridModel.Type += ",";
if (item != null)
_gridModel.Type += item.Type;
if (!string.IsNullOrEmpty(_gridModel.Sort))
_gridModel.Sort += ",";
if (item != null)
_gridModel.Sort += item.Sort;
答案 0 :(得分:15)
首先,将重构逻辑转换为函数。
_gridModel.Header = AppendItem(_gridModel.Header, item == null ? null : item.Header);
_gridModel.Width = AppendItem(_gridModel.Width, item == null ? null : item.Width);
...
...
string AppendItem(string src, string item)
{
if (! string.IsNullOrEmpty(src))
src += ",";
if (! string.IsNullOrEmpty(item))
src += item;
return src;
}
下一步可能是使用反射和属性:
编辑:充实的反射解决方案,但实际上还没有调试过它。
AppendProperties(_gridModel, item, "Header", "Width", "Align", ...)
void AppendProperty(object gridmodel, object item, params string[] propNames)
{
foreach (string propName in propNames)
AppendProperties(gridmodel, item, propName);
}
void AppendProperties(object gridmodel, object item, string propName)
{
PropertyInfo piGrid = gridmodel.GetType().GetProperty(propName);
if (piGrid != null && piGrid.PropertyType == typeof(string))
{
piGrid.SetValue(gridmodel,
piGrid.GetValue(gridmodel, null).ToString() + ",", null);
}
if (item == null) return;
PropertyInfo piItem = item.GetType().GetProperty(propName);
if (piItem != null)
{
piGrid.SetValue(gridmodel,
piGrid.GetValue(gridmodel, null).ToString()
+ piItem.GetValue(item, null).ToString(),
null);
}
}
答案 1 :(得分:7)
假设你有.NET 3.5:
string Filter(string input, SomeType item, Func<SomeType, string> extract)
{
if (!String.IsNullOrEmpty(input))
{
if (item == null) return ",";
else return "," + extract(item);
}
}
_gridModel.Header += Filter(_gridModel.Header, item, i => i.Header);
_gridModel.Width += Filter(_gridModel.Width, item, i => i.Width);
_gridModel.Align += Filter(_gridModel.Align, item, i => i.Align);
// etc...