关闭

反射,通过类名(字符串)获取类

标签: CreateInstanceReflection
4458人阅读 评论(0) 收藏 举报
分类:

一句话搞定的处理:

private static readonly string path = "GCForum";
public static UIViewController GetVC(string vcname)
{
	return (UIViewController)Assembly.Load (path).CreateInstance (path + "." + vcname);
}

如果考虑线程问题,最好加锁判断:

private static object lockHelper = new object();

public static MyCourse _mycourse = null;
public static MyCourseLoad _mycourseload= null;
public static UIViewController GetVC(string vcname)
{
	UIViewController vc;
	switch (vcname) 
	{
		case "MyCourse":
			vc = CreateMyCourse ();
		break;
		case "MyCourseLoad":
			vc = CreateMyCourseLoad ();
		break;
		default :
			return null;
	}
	return vc;
}

/// <summary>
/// 我的课程
/// </summary>
private static MyCourse CreateMyCourse()
{
	return CreateInstance<MyCourse>(_mycourse, path + ".MyCourse");
}
/// <summary>
/// 我的下载
/// </summary>
private static MyCourseLoad CreateMyCourseLoad()
{
	return CreateInstance<MyCourseLoad>(_mycourseload, path + ".MyCourseLoad");
}
/// <summary>
/// 实例化
/// </summary>
public static T CreateInstance<T>(T _instance, string className)
{
	if (_instance == null)
	{
		lock (lockHelper)
		{
			if (_instance == null)
			{
				_instance = (T)Assembly.Load(path).CreateInstance(className);
			}
		}
	}
	return _instance;
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2003587次
    • 积分:19015
    • 等级:
    • 排名:第465名
    • 原创:309篇
    • 转载:345篇
    • 译文:2篇
    • 评论:182条
    最新评论