日期:2014-05-17 浏览次数:21801 次
转载请注明本文地址:
http://blog.csdn.net/elezeor/article/details/11468507
这是前几天在编写Unity游戏时随手写的一个类,
考虑到其中还是有一些可学点的,
就将将关键部分提取出,
发上来了。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using CompanionArray = System.Collections.Generic.Dictionary<string,UnityEngine.Transform>;
public abstract class MembersBase<T> where T : new()
{
public CompanionArray companions;
private static T instance;
public static T Instance
{
get
{
if(null == instance)
instance = new T();
return instance;
}
}
protected MembersBase()
{
companions = new CompanionArray();
}
}
public class SelectedMembers : MembersBase<SelectedMembers>
{
public SelectedMembers():base(){}
}各位一看便知。
简单注释几点:
--首先要注意,要想将单例类继承,
基类需要为泛型类。
然后这样在子类中只需要将己类传入即可。
--where T: new T()
这个语句代表使用的这个泛型需要包含一个无参构造函数,
当然,这个也是可以限定多个条件的。具体自行谷歌:C# keyword where
--C#中的typedef
这个是顺带一提,
C#中使用C++的typedef功能就是像开头那样,
使用using 语句就可完成。
涉及到泛型尤其是名字很长的Dictionary时尤为好用。