探知,不断发现
探知不断发现
posts - 195,  comments - 109,  trackbacks - 2

我们想在每个button的action被调用的时候可以正确调用 动物们的吃的动作
于是我们写下如下的代码。 但是可惜的是效果不对 输出来的是

Cat eat
Cat eat

什么会这样呢? 不了解也先不管它了, 但是只要将 稍微改一下代码就行了,见底下的注释部分

LinqPaid V1.35.3通过


void Main()
{
    List<MockButton> list =
new List<MockButton>();

    List<IEat> animals =
new List<IEat>(){new Dog(),new Cat()};

    
foreach(var item in animals)
    {
        MockButton k =
new MockButton();
        k.Action =
delegate(){item.Eat();};
        /*更改成 
        IEat animal =item;
        k.Action =delegate(){animal.Eat();};
 
        */
        list.Add(k);
    }
    
foreach(var item in list)
    {
        item.Action();
    }
}
public class MockButton
{
    
public Action Action;
}

public interface IEat
{    
    
string Name{get;}
    
void Eat();
}

public class Dog:IEat
{
    
public string Name{get{return"Dog";}}
    
public void Eat()
    {
        (
this.Name +    " eat").Dump();
    }
}
public class Cat:IEat
{
    
public string Name{get{return"Cat";}}
    
public void Eat()
    {
        (
this.Name +" eat").Dump();
    }
}

posted on 2011-09-22 18:34 lovebanyi 阅读(56) 评论(0) 编辑 收藏
昵称:lovebanyi
园龄:6年6个月
粉丝:28
关注:12

<2011年9月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

搜索

 
 

常用链接

我的标签

随笔分类

随笔档案

文章分类

相册

朋友

最新评论

阅读排行榜

评论排行榜

推荐排行榜