由于Sophex规定,你可以写一个通用的函数来处理的任何一个List<>
或更好的IList<>
。
所以,你的例子会成为,
public string TestBadal<T>(IList<T> list)
{
return "test";
}
这是非常通用的,需要并暗示有关T
小。这对你想要执行的处理可能是足够的,但是,你不会说。
通常,您应该将您的方法签名视为调用者必须对该函数作出的承诺。您应该将承诺限于只有您的职能完成其工作所需的内容。通过这种方式,承诺更容易实现,并且您的功能可以在来自调用方的更少承诺的情况下得到更多的重用。
你的功能,因为它代表,doesen't确实需要一个参数,将更好地定义为string const
但说,你唯一想做的就是枚举,你可以使用的项目,
public string TestBadal<T>(IEnumerable<T> entities)
{
foreach(T entity in entities)
{
...
}
}
如果你的如果您需要了解列表类型的财产以后,你有两个选择合理的处理,尤其是涉及到EF性质,你可以做的数据源,
public string TestBadal<TEntity>(EntitySet<TEntity> entities)
where TEntity : class
{
...
}
。 要么你需要类型来实现一个特定的接口,这essentialy让你的功能非泛型,并可能与EF结合的尴尬。
public string TestBadal(IEnumerable<IDefinedType> definedTypeInstances)
{
foreach(IDefinedType instance in definedTypeInstances)
{
var x = instance.SomeDefinedProperty;
}
}
或者,你可以把函数的非通用部件为typed delegate参数,保持功能一般,可能是财产以后这样的。
public string TestBadal<T>(
IList<T> list,
Func<T, string> stringSelector)
{
var result = new StringBuilder();
for(var i = 0; i < list.Count; i++)
{
result.AppendLine(stringSelector(list[i])
}
return result.ToString();
}
你可以称之为一个lambda表达式的财产以后这样的这一功能,
var result = TestBadal(entities, e => e.SomeStringProperty);
我希望这个答案既给你一些想法,并说明你想要什么我的观点是正确的答案取决于你的功能来实现。
你想对所有列表做什么?这个选择会影响我会采取的方法。在你的例子中,你可以删除参数,解决问题,'TestBadal'仍然会返回''test''。 – Jodrell 2012-07-18 09:01:25
@Jodrell上面只是示例代码,我需要在列表上做一些计算然后返回字符串。所以我需要参数 – user867198 2012-07-19 05:46:20