开发者

Generic foreach loop in C#

The compiler, given the following code, tells me "Use of unassigned local variable '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(Collecti开发者_高级运维on<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. This definitely satisfies the definite assignment rules of any conforming C# compiler for that code snippet. Either you're using a non-conforming compiler or the error is from somewhere else.


This: 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜