重拾C#,以备Unity脚本之用。
引用类型、Class直接上代码练习:
public class HelloWorld : MonoBehaviour {
enum Days {
Monday,
Tuesday
}
struct Person {
public string name;
public int age;
public string sex;
public int height;
}
// Use this for initialization
void Start () {
Person aPerson = new Person ();
aPerson.name = "Lee";
aPerson.age = 27;
aPerson.sex = "man";
aPerson.height = 175;
Debug.Log (aPerson.name);
Console.WriteLine (aPerson.name);
Console.WriteLine (aPerson.age);
Console.WriteLine (Days.Tuesday);
object o = new object ();
Console.WriteLine (o.GetType ());
Console.WriteLine (o.ToString ());
Console.ReadLine ();
}
// Update is called once per frame
void Update () {
var school = new School (999);
Console.WriteLine (school.GetNumber ());
Console.WriteLine (School.GetFive ());
Console.WriteLine (school.Age);
school.Age = 27;
Console.ReadLine ();
}
void OnGUI()
{
GUI.skin.label.fontSize = 100;
GUI.Label(new Rect(10, 10, Screen.width, Screen.height), "Hello World Unity3D!");
}
}
Interface是接口的实现,只包含方法、委托或事件和属性的签名、不能包含字段。
Abstract抽象类:不能类直接初始化,可以作为父类来使用。
Interface和Abstract都不能实例化。
Abstract是一种继承关系,一个类只能使用一次继承关系。
可以通过继承多个接口实现多重继承(一个类可以实现多个interface)。
使用泛型类型可以最大限度地重用代码、保护类型的安全以及提高性能。
泛型最常见的用途是创建集合类。
.NET Framework 类库在 System.Collections.Generic 命名空间中包含几个新的泛型集合类。应尽可能地使用这些类来代替普通的类,如 System.Collections命名空间中的 ArrayList。
可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。
可以对泛型类进行约束以访问特定数据类型的方法。
关于泛型数据类型中使用的类型的信息可在运行时通过使用反射获取。
// Declare the generic class.
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int.
GenericList<int> list1 = new GenericList<int>();
// Declare a list of type string.
GenericList<string> list2 = new GenericList<string>();
// Declare a list of type ExampleClass.
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}