在C#泛型foreach循环 [英] Generic foreach loop in C#

查看:176
本文介绍了在C#泛型foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器,因为下面的代码,告诉我:未分配使用局部变量的'X'。任何想法

 公共委托y功能< X,Y>(X X); 

公共类地图< X,Y>
{
私有函数和LT; X,Y> F;

公共地图(功能F)
{
F = F;
}

公文集< Y>在(收集和LT; X> XS){
名单,LT; Y> YS =新的List< Y>();
的foreach(在XS X X)
{$ B $宽x X2 = X; // ys.Add(F(X));
}
返回YS;
}
}


解决方案

在。修复它编译罚款对我来说是明显的错误。

 公共委托y功能< X,Y>(X X); 

公共类地图< X,Y>
{
私有函数和LT; X,Y> F;

公共地图(功能< X,Y&F)的温度
{
F = F;
}

公众的ICollection< Y>在(ICollection的< X> XS){
名单,LT; Y> YS =新的List< Y>();
的foreach(在XS X X)
{$ B $宽x X2 = X; // ys.Add(F(X));
}
返回YS;
}
}


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(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;
    }
}

这篇关于在C#泛型foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆