gpt4 book ai didi

c# - 如何重构这段代码?

转载 作者:太空狗 更新时间:2023-10-29 23:56:20 25 4
gpt4 key购买 nike

我如何将此代码重构为一种方法或其他方法?

            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;

最佳答案

首先,将逻辑重构到一个函数中。

_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);
}
}

关于c# - 如何重构这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1493743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com