我有一个名为ParentPropertyAttribute的类文件,其类型属性如下:
public Type PropertyType { get; set; }
在我的一个类中,我需要根据传递的类型做一些工作。现在,我使用if else条件,如下所示:
if (parentPropertyAttribute.PropertyType == typeof(string))
{
return (parentList as IList<string>).Select(item => new SelectItem() { Value = item, Text = item }).OrderBy(selectItem => selectItem.Text);
}
else if (parentPropertyAttribute.PropertyType == typeof(XYZ))
{
return (parentList as IList<XYZ>).Select(x=> new SelectItem() { Value = item, Text = item }).OrderBy(selectItem => selectItem.Text);
}
上面的问题是,如果将来有任何其他类型,if else情况会增加。是否有一种优化的方法来动态分配类型(在这个例子中是字符串/XYZ)来实现这一点?
欢迎输入。
致意。
由于您在IList<>
接口上使用的唯一东西来自IEnumerable<>
接口,因此有可能您可以这样做:
return ((IEnumerable)parentList).Cast<object>()
.Select(item => new SelectItem { Value = item, Text = item.ToString() })
.OrderBy(selectItem => selectItem.Text)
.ToList();
这取决于列表中所有有效类型是否具有适合此目的的ToString()
实现。
注意,如果您知道所有类型都不是值类型(需要装箱才能转换为object
),则((IEnumerable)parentList).Cast<object>()
可以简化为((IEnumerable<object>)parentList)
。
当然可以。您只需要在代码中添加更多泛型。请参考这个例子:
class SmartListItem
{
public string Name { get; set; }
}
class SmartList
{
private System.Collections.IList list;
public SmartList(System.Collections.IList list)
{
this.list = list;
}
public List<T> FilterPropertyType<T>(Func<T, bool> query)
{
return list.Cast<T>().Where(query).ToList();
}
}
你可以使用这个"SmartList"以不同的方式(没有使用ParentType,因为没有必要):
var stringList = new SmartList(new[] { "Rob", "Liam" });
var matches = stringList.FilterPropertyType<string>(s => s.Contains("Rob"));
或者使用类更好:
var classList = new SmartList(new []{
new SmartListItem { Name = "Rob" },
new SmartListItem { Name = "Liam" }
});
var matches = classList.FilterPropertyType<SmartListItem>(smi => smi.Name.Contains("Rob"));
使用它可以避免PropertyType的切换大小写,并直接在列表项上执行查询。