public void OnAfterDeserialize() { if (Type.GetType(m_Identifier) == null) { //Handles cases where the component is migrated to another assembly (for example if using Unity's assembly definitions feature const char separator = ','; const string separatorString = ","; string[] splittedAssemblyQualifiedName = m_Identifier.Split(separator); if (splittedAssemblyQualifiedName.Length >= 5) { string typeName = String.Join(separatorString, splittedAssemblyQualifiedName.SubArray(0, splittedAssemblyQualifiedName.Length - 4)); //As you can see with this example: //"FluffyUnderware.Curvy.CurvySplineSegment, ToolBuddy.Curvy, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" //the 4 last elements do not contain the type name. Keep in mind that a type name can include a ',' like Dictionary<int, List<double>> #if NETFX_CORE Type[] knownTypes = this.GetType().GetAllTypes(); #else Type[] knownTypes = TypeExt.GetLoadedTypes(); #endif Type type = knownTypes.FirstOrDefault(t => t.FullName == typeName); if (type != null) { m_Identifier = type.AssemblyQualifiedName; } } } }
static void loadItems() { List <Type> types = new List <Type>(); foreach (Type t in TypeExt.GetLoadedTypes()) { if (t.IsSubclassOf(typeof(DTToolbarItem))) { object[] attribs = t.GetCustomAttributes(typeof(ToolbarItemAttribute), true); if (attribs != null && attribs.Length > 0) { types.Add(t); } } } foreach (DTProject prj in DT.Projects) { prj.ToolbarItems.Clear(); } foreach (Type t in types) { Activator.CreateInstance(t); } foreach (DTProject prj in DT.Projects) { prj.ToolbarItems.Sort(); } }
static NoggolloquyRegistration() { foreach (var interf in TypeExt.GetInheritingFromInterface <IProtocolRegistration>( loadAssemblies: false)) { IProtocolRegistration regis = Activator.CreateInstance(interf) as IProtocolRegistration; regis.Register(); } }
static LinkInterfaceMappingInternal() { if (!LinkInterfaceMapping.AutomaticRegistration) { return; } foreach (var interf in TypeExt.GetInheritingFromInterface <ILinkInterfaceMapping>( loadAssemblies: true)) { ILinkInterfaceMapping?mapping = Activator.CreateInstance(interf) as ILinkInterfaceMapping; Mappings[mapping !.GameCategory] = mapping !.InterfaceToObjectTypes;
static LinkInterfaceMappingInternal() { if (!LinkInterfaceMapping.AutomaticRegistration) { return; } foreach (var interf in TypeExt.GetInheritingFromInterface <ILinkInterfaceMapping>( loadAssemblies: true)) { Register((Activator.CreateInstance(interf) as ILinkInterfaceMapping) !); } }
protected K GenerateNewId() { if (typeof(K) == typeof(Guid)) { return(TypeExt.ConvertType <K>(Util.SeqGuid())); } if (typeof(K) == typeof(int) || typeof(K) == typeof(long)) { return(TypeExt.ConvertType <K>(0)); } throw new NotSupportedException("不支持的主键类型"); }
public Translator( Type nullTranslator, Type genericCaster, Type loquiTranslation, Type enumTranslation) { this.genericCaster = genericCaster; this.loquiTranslation = loquiTranslation; this.enumTranslation = enumTranslation; var nullCasterType = genericCaster.MakeGenericType(typeof(Object)); var nullTranslation = Activator.CreateInstance(nullTranslator) !; NullTranslationItem = GetResponse <ObjTransl> .Succeed((ObjTransl)Activator.CreateInstance(nullCasterType, new object[] { nullTranslation }) !); var genInterfType = typeof(ObjTransl).GetGenericTypeDefinition(); foreach (var kv in TypeExt.GetInheritingFromGenericInterface(genInterfType)) { if (kv.Value.IsAbstract) { continue; } if (kv.Value.Equals(genericCaster)) { continue; } if (kv.Value.IsGenericTypeDefinition) { GenericTypes.Add(kv.Value); continue; } Type transItemType = kv.Key.GetGenericArguments()[0]; try { SetTranslator( GetCaster(kv.Value, transItemType), transItemType); } catch (Exception ex) { typeDict[transItemType] = GetResponse <ObjTransl> .Fail(ex); } } }
static void LoadProjects() { mProjects.Clear(); List <Type> types = new List <Type>(); foreach (Type t in TypeExt.GetLoadedTypes()) { if (t.IsSubclassOf(typeof(DTProject))) { types.Add(t); } } foreach (Type t in types) { DTProject newProject = (DTProject)Activator.CreateInstance(t); mProjects.Add(newProject.Identifier, newProject); } }
protected override void OnInit() { base.OnInit(); var baseSet = new Func <EntityQueryBuilder>(() => World.Mgr.GetEntities() .With <AudioPlayerId>() .With <StandardAudioPlayerComponent>()); playerSet = baseSet().AsSet(); playAudioSet = baseSet().With <ResourceHandle <AudioResource> >() .With <PlayAudioRequest>() .AsSet(); stopAudioSet = baseSet().With <StopAudioRequest>().AsSet(); toDisposeSet = baseSet().With <AudioFireAndForgetComponent>().AsSet(); typeName = TypeExt.GetFriendlyName(typeof(StandardAudioPlayerComponent)); DependencyResolver.Add(() => ref worldTime); }
public static Type[] GetGenericParametersTypes(this SerializedProperty property) { Type parentType = property.serializedObject.targetObject.GetType(); string[] path = property.GetFullPropertyPath(); string firstName = path[0]; FormatArrayNaming(ref firstName); FieldInfo fieldInfo = null; fieldInfo = GetFieldInfo(firstName, parentType); while (fieldInfo == null && parentType.BaseType != null) { parentType = parentType.BaseType; fieldInfo = GetFieldInfo(firstName, parentType); } Type type = fieldInfo.FieldType; if (type.IsArray) { type = type.GetElementType(); } for (int i = 1; i < path.Length; i++) { if (type != null) { parentType = type; } type = GetFieldInfo(path[i], parentType).FieldType; } if (type != null) { return(TypeExt.GetGenericHierarchy(type.ToString())); } return(null); }
public static object GetValue(this Request requset, string name, Type type) { if (type != typeof(string) && type.IsClass) { return(requset.GetObject(name, type)); } string value = requset.Form[name]; if (value == null) { value = requset.Query[name]; } if (value == null) { throw new Exception("不能获取名称为" + name + "的值"); } if (type == typeof(string) || type == typeof(char) || type == typeof(bool) || type == typeof(byte) || type == typeof(short) || type == typeof(int) || type == typeof(uint) || type == typeof(long) || type == typeof(ulong) || type == typeof(float) || type == typeof(double) || type == typeof(decimal) || type == typeof(Guid) || type == typeof(DateTime)) { return(TypeExt.ConvertType(type, value)); } return(SerializeExt.JsonTo(value, type)); }
public static void GenerateInterfaceGetters(ObjectGeneration obj, FileGeneration fg) { TypeExt.LoadAssemblies(); foreach (var interf in obj.Interfaces) { switch (interf.Type) { case LoquiInterfaceDefinitionType.IGetter: case LoquiInterfaceDefinitionType.Dual: break; case LoquiInterfaceDefinitionType.Direct: case LoquiInterfaceDefinitionType.ISetter: default: continue; } Type t = GetType(interf.GetterInterface); if (t == null) { throw new ArgumentException($"Could not find interface: {interf.GetterInterface}"); } } }
static XmlTranslator() { foreach (var kv in TypeExt.GetInheritingFromGenericInterface(typeof(IXmlTranslation <>))) { Type transItemType = kv.Key.GetGenericArguments()[0]; try { object xmlTransl = Activator.CreateInstance(kv.Value); var xmlConverterGenType = typeof(XmlTranslationCaster <>).MakeGenericType(transItemType); IXmlTranslation <Object> transl = Activator.CreateInstance(xmlConverterGenType, args: new object[] { xmlTransl }) as IXmlTranslation <Object>; SetTranslator(transl, transItemType); } catch (Exception ex) { var resp = typeDict.TryCreateValue( transItemType, () => { return(new NotifyingItem <GetResponse <IXmlTranslation <Object> > >()); }).Value = GetResponse <IXmlTranslation <object> > .Fail(ex); } } }
private Type GetTargetedType(bool checkForSerializable = true) { Type type = m_type.GetClass(); if (type == null) { string typeDefenition = m_type.ToString(); var parts = typeDefenition.Split(new [] { "namespace" }, StringSplitOptions.RemoveEmptyEntries)[1].Split(' ')[1].Split('\n'); typeDefenition = parts[0].Trim() + "." + m_type.name; type = TypeExt.GetType(typeDefenition); } if (checkForSerializable && type != null && !type.IsSerializable) { throw new Exception($"{type} is not serializable"); } return(type); }
protected override void OnUpdate() { base.OnUpdate(); if (withoutIdSet.Count > 0) { Span <Entity> entities = stackalloc Entity[withoutIdSet.Count]; withoutIdSet.GetEntities().CopyTo(entities); foreach (ref readonly var entity in entities) { entity.Set(new AudioPlayerId(selfLastMaxId++)); } } var maxId = 0; foreach (var entity in playerSet.GetEntities()) { maxId = Math.Max(maxId, entity.Get <AudioPlayerId>().Id); } // for memory usage, don't put this call into the foreach since stackalloc is only freed when this method itself is finished Span <Entity> clientUpdated = stackalloc Entity[playerSet.Count]; foreach (var(featureEntity, feature) in Features) { var update = false; var previousId = 0; if (!clientLastMaxId.TryGetValue(feature, out var clientMaxId) || clientMaxId < maxId) { previousId = clientMaxId; clientLastMaxId[feature] = maxId; update = true; } if (update) { var updatedCount = 0; foreach (var entity in playerSet.GetEntities()) { if (entity.Get <AudioPlayerId>().Id > previousId) { clientUpdated[updatedCount++] = entity; } } using var writer = new DataBufferWriter(updatedCount); writer.WriteInt((int)EAudioSendType.RegisterPlayer); writer.WriteInt(updatedCount); foreach (var entity in clientUpdated.Slice(0, updatedCount)) { writer.WriteInt(entity.Get <AudioPlayerId>().Id); writer.WriteStaticString(TypeExt.GetFriendlyName(entity.Get <AudioPlayerType>().Type)); } if (feature.Driver.Broadcast(feature.PreferredChannel, writer.Span) < 0) { throw new InvalidOperationException("Couldn't send data!"); } } } }
void DoInterpolate() { if (!mSpline.IsInitialized) { return; } System.Type metaDataType; { if (String.IsNullOrEmpty(MetaDataType.Value)) { metaDataType = null; } else { #if NETFX_CORE Type[] knownTypes = this.GetType().GetAllTypes(); #else Type[] knownTypes = TypeExt.GetLoadedTypes(); #endif metaDataType = knownTypes.FirstOrDefault(t => t.FullName == MetaDataType.Value); } } bool calc = !Input.IsNone; if (calc) { float f = (UseWorldUnits.Value) ? mSpline.DistanceToTF(Input.Value) : Input.Value; if (StorePosition.IsNone == false) { StorePosition.Value = (UseCache.Value) ? mSpline.InterpolateFast(f) : mSpline.Interpolate(f); } if (StoreTangent.IsNone == false) { StoreTangent.Value = mSpline.GetTangent(f); } if (StoreUpVector.IsNone == false) { StoreUpVector.Value = mSpline.GetOrientationUpFast(f); } if (StoreRotation.IsNone == false) { StoreRotation.Value = (StoreUpVector.IsNone) ? mSpline.GetOrientationFast(f) : Quaternion.LookRotation(mSpline.GetTangent(f), StoreUpVector.Value); } if (StoreScale.IsNone == false) { float localF; CurvySplineSegment segment = mSpline.TFToSegment(f, out localF); CurvySplineSegment nextControlPoint = segment.Spline.GetNextControlPoint(segment); if (ReferenceEquals(segment, null) == false) { StoreScale.Value = nextControlPoint ? Vector3.Lerp(segment.transform.lossyScale, nextControlPoint.transform.lossyScale, localF) : segment.transform.lossyScale; } else { StoreScale.Value = Vector3.zero; } } if (StoreTF.IsNone == false) { StoreTF.Value = f; } if (StoreDistance.IsNone == false) { StoreDistance.Value = (UseWorldUnits.Value) ? Input.Value : mSpline.TFToDistance(f); } if (metaDataType != null) { if (metaDataType.IsSubclassOf(typeof(CurvyMetadataBase)) == false) { //this if statement's branch does not exclude classes inheriting from CurvyMetadataBase but not from CurvyInterpolatableMetadataBase, but that's ok, those classes are handled below Debug.LogError("Meta data type " + metaDataType.FullName + " should be a subclass of CurvyInterpolatableMetadataBase<T>"); } else { if (StoreMetadata.IsNone == false) { MethodInfo genericMethodInfo = mSpline.GetType().GetMethod("GetMetadata").MakeGenericMethod(metaDataType); StoreMetadata.Value = (Object)genericMethodInfo.Invoke(mSpline, new System.Object[] { f }); } if (StoreInterpolatedMetadata.IsNone == false) { Type argumentType = GetInterpolatableMetadataGenericType(metaDataType); if (argumentType == null) { Debug.LogError("Meta data type " + metaDataType.FullName + " should be a subclass of CurvyInterpolatableMetadataBase<T>"); } else { MethodInfo genericMethodInfo = mSpline.GetType().GetMethod("GetInterpolatedMetadata").MakeGenericMethod(metaDataType, argumentType); StoreInterpolatedMetadata.SetValue(genericMethodInfo.Invoke(mSpline, new System.Object[] { f })); } } } } CurvySplineSegment seg = null; float segF = 0; if (StoreSegment.IsNone == false) { seg = getSegment(f, out segF); StoreSegment.Value = seg.gameObject; } if (StoreSegmentF.IsNone == false) { if (!seg) { seg = getSegment(f, out segF); } StoreSegmentF.Value = segF; } if (StoreSegmentDistance.IsNone == false) { if (!seg) { seg = getSegment(f, out segF); } StoreSegmentDistance.Value = seg.LocalFToDistance(segF); } } // General if (StoreLength.IsNone == false) { StoreLength.Value = mSpline.Length; } if (StoreCount.IsNone == false) { StoreCount.Value = mSpline.Count; } }
protected override void OnDependenciesResolved(IEnumerable <object> dependencies) { base.OnDependenciesResolved(dependencies); playerManager.AddListener(TypeExt.GetFriendlyName(typeof(StandardAudioPlayerComponent)), OnRead); }
public void GetTypeName(string name, string result) { TypeExt.GetName(name).Should().Be(result); }
public static Assembly FindResourceDLL(string name) { //BUG will return the wrong dll if there is another dll that starts with the same name return(TypeExt.GetLoadedAssemblies().FirstOrDefault(asm => asm.FullName.StartsWith(name))); }
/// <summary> /// 按属性路径设置对象中某个属性的值,如果路径中的对象为空则创建 /// 说明: /// 1、列表对象只支持List<T>类型。 /// 2、动态构建的对象(为空时)需要有无参的公共构造函数,否则请在父级对象构造时一并构建。 /// 3、设置对象值时将自动进行类型转换,如果无法自动转换,将使用类型默认值(不会抛出异常)。 /// /// 路径格式: [PropertyName|Index] /// eg: [CostList][1][Name] /// /// </summary> /// <param propertyPath="obj"></param> /// <param propertyPath="propertyPath"></param> /// <param propertyPath="value"></param> public static void SetValue(object obj, string propertyPath, object value) { var match = Regex.Match(propertyPath, @"^\[(\w+)\]"); if (!match.Success) { return; } var type = obj.GetType(); var pname = match.Groups[1].Value; if (Regex.IsMatch(pname, @"^\d+$")) { //处理数组索引 var index = int.Parse(pname); if (type.IsGenericType && Array.Exists(type.GetInterfaces(), t => t.GetGenericTypeDefinition() == typeof(IList <>))) { var genericArgs = type.GetGenericArguments(); var itemType = genericArgs[0]; var listobj = obj as IList; object item; if (index == listobj.Count) { item = Activator.CreateInstance(itemType); listobj.Add(item); } else if (index < listobj.Count) { item = listobj[index]; } else { throw new Exception("索引错误"); } SetValue(item, propertyPath.Substring(match.Length), value); } } var prop = type .GetProperty(pname, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.Public); if (prop == null) { return; } var ptype = prop.PropertyType; if (ptype.IsClass && ptype != typeof(string)) { var pvalue = prop.GetValue(obj); if (pvalue == null) { pvalue = Activator.CreateInstance(ptype); prop.SetValue(obj, pvalue); } SetValue(pvalue, propertyPath.Substring(match.Length), value); } else { prop.SetValue(obj, TypeExt.ConvertType(ptype, value)); } }