/// <summary> /// 该方法性能有问题,,请一定谨慎调用 /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static Type GetType(string typeName) { Type resType = null; if (typeName.Contains("UnityEngine")) { resType = Type.GetType(typeName + ",UnityEngine"); if (resType == null) { LCLog.LogError("GetType UnityEngine 失败>>>>", typeName); return(null); } return(resType); } if (typeName.Contains("LCHelp")) { resType = Type.GetType(typeName + ",LCHelp"); if (resType == null) { LCLog.LogError("GetType LCHelp 失败>>>>", typeName); return(null); } return(resType); } if (typeName.Contains("LCECS")) { resType = Type.GetType(typeName + ",LCECS"); if (resType == null) { LCLog.LogError("GetType LCECS 失败>>>>", typeName); return(null); } return(resType); } //基础程序集 resType = Type.GetType(typeName); if (resType != null) { return(resType); } //项目程序集 if (resType == null) { if (Application.isPlaying) { return(GetTypeInPlaying(typeName)); } else { return(GetTypeInStop(typeName)); } } return(resType); }
//运行模式下GetType private static Type GetTypeInPlaying(string typeName) { InitCollectAllTypes(); for (int i = 0; i < AllTypeItems.Count; i++) { if (AllTypeItems[i].FullName == typeName) { return(AllTypeItems[i]); } } LCLog.LogError("GetTypeInPlaying 失败>>>>", typeName); return(null); }
//非运行模式下GetType private static Type GetTypeInStop(string typeName) { Type resType = null; //项目程序集 string asPath = Path.GetFullPath(@".\Library\ScriptAssemblies\Assembly-CSharp.dll"); Assembly ass = Assembly.LoadFile(@asPath); resType = ass.GetType(typeName); if (resType == null) { LCLog.LogError("GetTypeInStop 失败>>>>", typeName); } return(resType); }
/// <summary> /// 设置类中字段值 /// </summary> public static void SetTypeFieldValue(object obj, string fieldName, object value) { if (obj == null) { return; } try { FieldInfo info = obj.GetType().GetField(fieldName); info.SetValue(obj, value); } catch (Exception e) { LCLog.LogError("设置类中字段值失败", obj.GetType(), fieldName, e); } }
/// <summary> /// 创建对应实例 /// </summary> /// <typeparam name="T">返回类型</typeparam> /// <param name="fullName">实例类型全名</param> /// <param name="parameters">构造参数</param> /// <returns>返回类型</returns> public static T CreateInstanceByType <T>(string fullName, params object[] parameters) { Type type = GetType(fullName); if (type == null) { LCLog.LogError("CreateInstanceByType 没有找到指定类型>>>>", fullName); return(default(T)); } object obj = null; try { obj = Activator.CreateInstance(type, parameters); } catch (Exception e) { LCLog.LogError("CreateInstanceByType 异常>>>>", e); obj = default(T); } return((T)obj); }