[英]Generic foreach loop in C#
The compiler, given the following code, tells me "Use of unassigned local variable 'x'." 给定以下代码,编译器告诉我“使用未分配的局部变量'x'。” Any thoughts? 有什么想法吗?
public delegate Y Function<X,Y>(X x);
public class Map<X,Y>
{
private Function<X,Y> F;
public Map(Function f)
{
F = f;
}
public Collection<Y> Over(Collection<X> xs){
List<Y> ys = new List<Y>();
foreach (X x in xs)
{
X x2 = x;//ys.Add(F(x));
}
return ys;
}
}
After fixing the obvious errors it compiles fine for me. 在解决了明显的错误后,它对我来说很好。
public delegate Y Function<X,Y>(X x);
public class Map<X,Y>
{
private Function<X,Y> F;
public Map(Function<X,Y> f)
{
F = f;
}
public ICollection<Y> Over(ICollection<X> xs){
List<Y> ys = new List<Y>();
foreach (X x in xs)
{
X x2 = x;//ys.Add(F(x));
}
return ys;
}
}
The language specification defines foreach
statement as the equivalent of a while
loop, in which the loop variable is assigned to the Current
property of the enumerator object. 语言规范将foreach
语句定义为while
循环的等价物,其中循环变量被赋值给枚举器对象的Current
属性。 This definitely satisfies the definite assignment rules of any conforming C# compiler for that code snippet. 这绝对满足了该代码片段的任何符合C#编译器的明确赋值规则。 Either you're using a non-conforming compiler or the error is from somewhere else. 您使用的是不合格的编译器,或者错误来自其他地方。
This: public Map(Function f)
这个: public Map(Function f)
Should be: 应该:
public Map(Function<X,Y> f)
And this: 和这个:
public Collection<Y> Over(Collection<X> xs)
Should be: 应该:
public ICollection<Y> Over(ICollection<X> xs)
Or: 要么:
public List<Y> Over(Collection<X> xs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.