其他分享
首页 > 其他分享> > 泛型种树(generic) 代码

泛型种树(generic) 代码

作者:互联网

再这个案例中我们,为什么要使用泛型约束

使用约束的原因 约束指定类型参数的功能和预期。 声明这些约束意味着你可以使用约束类型的操作和方法调用。 如果泛型类或 方法对泛型成员使用除简单赋值之外的任何操作或调用 System.Object 不支持的任何方法,则将对类型参数应用 约束。 例如,基类约束告诉编译器,仅此类型的对象或派生自此类型的对象可用作类型参数。 编译器有了此保证 后,就能够允许在泛型类中调用该类型的方法。

案例来源:https://www.cnblogs.com/netbatman/p/10374072.html

实例使用泛型来种树(模拟下蚂蚁森林种树):

现在森林里可以种其他的树了(柠条,樟子松)。那我们添加2个类,修改People类,和Main方法,那有什么办法可以不修改People类的呢?

现在我们创建一个抽象类TreeBase:

    public abstract class TreeBase
    {
        public abstract string GetTreeName();
        public abstract int needEnergy();
    }

    public class SuosuoTree: TreeBase
    {
        //种植梭梭树需要的能量
        public override int needEnergy()
        {
            return 17900;
        }
        public override string GetTreeName()
        {
            return "梭梭树";
        }
    }

    public class NingTiaoTree : TreeBase
    {
        //种植柠条需要的能量
        public override int needEnergy()
        {
            return 16930;
        }
        public override string GetTreeName()
        {
            return "柠条";
        }
    }

    public class ZhangZiSongTree : TreeBase
    {
        //种植樟子松需要的能量
        public override int needEnergy()
        {
            return 146210;
        }
        public override string GetTreeName()
        {
            return "樟子松";
        }
    }

复制代码

重新构造后的People:修改后添加了新的树苗,就不用修改People类了。
复制代码

    public class People
    {
        //姓名
        public string name { get; set; }

        //能量
        public int energy { get; set; }

        public void Plant<T>(T tree) where T:TreeBase
        {
            if(energy< tree.needEnergy())
            {
                Console.WriteLine("能量不足");
            }
            else
            {
                energy = energy- tree.needEnergy();
                Console.WriteLine($"恭喜{name},{tree.GetTreeName()}种植成功,获得成就!!");
            }
        }
    }

复制代码

 

小明也可以种不同的树了:

    class Program
    {
        static void Main(string[] args)
        {
            People xiaoming = new People
            {
                name = "小明",
                energy = 200000
            };

            xiaoming.Plant(new SuosuoTree());
            xiaoming.Plant(new NingTiaoTree());
            xiaoming.Plant(new ZhangZiSongTree());

            Console.WriteLine("剩余能量:"+xiaoming.energy);

            xiaoming.Plant(new ZhangZiSongTree());

            Console.Read();

        }
    }

 

标签:return,string,People,generic,override,needEnergy,种树,泛型,public
来源: https://www.cnblogs.com/cdaniu/p/15325620.html