Ste*_*ane 5 c# generics refactoring
更新:我应该在原帖中提到我想在这里学习更多关于泛型的知识.我知道这可以通过修改基类或创建两个文档类实现的接口来完成.但是为了这个练习,我只对那些不需要对文档类或它们的基类进行任何修改的解决方案感兴趣.我认为这个问题涉及扩展方法的事实会暗示这一点.
我写了两个几乎相同的泛型扩展方法,并试图找出如何将它们重构为单个方法.它们的区别仅在于,一个在List上运行,另一个在List上运行,我感兴趣的属性是AssetDocument的AssetID和PersonDocument的PersonID.尽管AssetDocument和PersonDocument具有相同的基类,但每个类中都定义了属性,因此我认为这没有帮助.我试过了
public static string ToCSVList<T>(this T list) where T : List<PersonDocument>, List<AssetDocument>
Run Code Online (Sandbox Code Playgroud)
我想我可能会测试类型并采取相应的行动,但这会导致语法错误
类型参数'T'继承冲突的约束
这些是我想要重构为单一方法的方法,但也许我只是过分了,他们最好保持原样.我想听听你的想法.
public static string ToCSVList<T>(this T list) where T : List<AssetDocument>
{
var sb = new StringBuilder(list.Count * 36 + list.Count);
string delimiter = String.Empty;
foreach (var document in list)
{
sb.Append(delimiter + document.AssetID.ToString());
delimiter = ",";
}
return sb.ToString();
}
public static string ToCSVList<T>(this T list) where T : List<PersonDocument>
{
var sb = new StringBuilder(list.Count * 36 + list.Count);
string delimiter = String.Empty;
foreach (var document in list)
{
sb.Append(delimiter + document.PersonID.ToString());
delimiter = ",";
}
return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)
您的实现基本上是重新实现string.Join方法,因此您可能会尝试使用一些LINQ使其更简单和更通用:
public static string ToCSVList<T>(this IEnumerable<T> collection)
{ return string.Join(",", collection.Select(x => x.ToString()).ToArray()); }
public static string ToCSVList(this IEnumerable<AssetDocument> assets)
{ return assets.Select(a => a.AssetID).ToCSVList(); }
public static string ToCSVList(this IEnumerable<PersonDocument> persons)
{ return persons.Select(p => p.PersonID).ToCSVList(); }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1017 次 |
| 最近记录: |