zoukankan      html  css  js  c++  java
  • 列表和字典

    BadGuy

    using UnityEngine;
    using System.Collections;
    using System; //这允许 IComparable 接口
    
    //这是您将存储在
    //不同集合中的类。为了使用
    //集合的 Sort() 方法,此类需要
    //实现 IComparable 接口。
    public class BadGuy : IComparable<BadGuy>
    {
        public string name;
        public int power;
    
        public BadGuy(string newName, int newPower)
        {
            name = newName;
            power = newPower;
        }
    
        //IComparable 接口需要
        //此方法。
        public int CompareTo(BadGuy other)
        {
            if(other == null)
            {
                return 1;
            }
    
            //返回力量差异。
            return power - other.power;
        }
    }

    SomeClass

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class SomeClass : MonoBehaviour
    {
        void Start () 
        {
            //这是创建列表的方式。注意如何在
            //尖括号 (< >) 中指定类型。
            List<BadGuy> badguys = new List<BadGuy>();
    
            //这里将 3 个 BadGuy 添加到列表
            badguys.Add( new BadGuy("Harvey", 50));
            badguys.Add( new BadGuy("Magneto", 100));
            badguys.Add( new BadGuy("Pip", 5));
    
            badguys.Sort();
    
            foreach(BadGuy guy in badguys)
            {
                print (guy.name + " " + guy.power);
            }
    
            //这会清除列表,使其
            //为空。
            badguys.Clear();
        }
    }

    SomeOtherClass

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class SomeOtherClass : MonoBehaviour 
    {
        void Start ()
        {
            //这是创建字典的方式。注意这是如何采用
            //两个通用术语的。在此情况中,您将使用字符串和
            //BadGuy 作为两个值。
            Dictionary<string, BadGuy> badguys = new Dictionary<string, BadGuy>();
    
            BadGuy bg1 = new BadGuy("Harvey", 50);
            BadGuy bg2 = new BadGuy("Magneto", 100);
    
            //可以使用 Add() 方法将变量
            //放入字典中。
            badguys.Add("gangster", bg1);
            badguys.Add("mutant", bg2);
    
            BadGuy magneto = badguys["mutant"];
    
            BadGuy temp = null;
    
            //这是一种访问字典中值的更安全
            //但缓慢的方法。
            if(badguys.TryGetValue("birds", out temp))
            {
                //成功!
            }
            else
            {
                //失败!
            }
        }
    }
  • 相关阅读:
    PLSQL表
    CentOS服务器下JavaEE环境搭建指南(远程桌面+JDK+Tomcat+MySQL)
    数据分析业务调研
    Apache -poi
    Python入门经典
    高性能Linux服务器构建实战:运维监控、性能调优与集群应用
    新编 中文版CorelDRAW入门与提高
    早该这样学!Photoshop比你想的简单
    跟老男孩学Linux运维:MySQL入门与提高实践
    SQL查询的艺术
  • 原文地址:https://www.cnblogs.com/Mr-Prince/p/14142886.html
Copyright © 2011-2022 走看看