/// <summary> /// Dumps everything of a single type into the cache from the filesystem for BackingData /// </summary> /// <typeparam name="T">the type to get and store</typeparam> /// <returns>full or partial success</returns> public static bool LoadAllToCache(Type objectType) { if (!objectType.GetInterfaces().Contains(typeof(IData))) return false; var fileAccessor = new NetMud.DataAccess.FileSystem.BackingData(); var typeDirectory = fileAccessor.BaseDirectory + fileAccessor.CurrentDirectoryName + objectType.Name + "/"; if (!fileAccessor.VerifyDirectory(typeDirectory, false)) { LoggingUtility.LogError(new AccessViolationException(String.Format("Current directory for type {0} does not exist.", objectType.Name))); return false; } var filesDirectory = new DirectoryInfo(typeDirectory); foreach (var file in filesDirectory.EnumerateFiles()) { try { BackingDataCache.Add(fileAccessor.ReadEntity(file, objectType)); } catch(Exception ex) { LoggingUtility.LogError(ex); //Let it keep going } } return true; }
public void AppendBaseClasses(Type type) { if (((type.BaseType == null) || (type.BaseType == typeof(object))) && (type.GetInterfaces().Length == 0)) { return; } // Dont use base types in comparing declarations.. someday, would be good to do a more intelligent compare (implemented interfaces removed is possibly a breaking change?) AppendMode restore = _mode; _mode &= ~AppendMode.Text; AppendText(" : "); if ((type.BaseType != null) && (type.BaseType != typeof(object))) { AppendType(type.BaseType); AppendText(", "); } foreach (Type intf in type.GetInterfaces()) { AppendType(intf); AppendText(", "); } RemoveCharsFromEnd(2); _mode = restore; }
/// <summary> /// Initialises the Factory property based on the type to which the attribute is applied. /// </summary> /// <param name="decoratedType">The type to which the attribute is applied</param> public virtual void Initialise(Type decoratedType) { if (Initialised) { throw new InvalidOperationException("Already initialised!"); } var name = decoratedType.Name.ToProperCase(); var alias = decoratedType.Name.ToCamelCase(); if (Name == null) { Name = name; } if (Alias == null) { Alias = alias; } if (AllowedChildren == null && decoratedType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IListViewDocumentType<>))) { var type = decoratedType.GetInterfaces().First(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IListViewDocumentType<>)).GetGenericArguments().First(); if (type.GetCodeFirstAttribute<DocumentTypeAttribute>(false) != null) { AllowedChildren = new Type[] { type }; } } Initialised = true; }
private bool ExcludedTypes(Type type) { return type != typeof(SecureSocketStyxEngine) && !type.GetInterfaces().Contains(typeof(IHostConfiguration)) && !type.GetInterfaces().Contains(typeof(IHandshakeNegotiator)) && !type.GetInterfaces().Contains(typeof(ILogger)); }
/// <summary> /// Determines whether the specified property type is a collection. /// </summary> /// <param name="propertyType">Type of the property.</param> /// <returns></returns> public static bool IsCollectionType(Type propertyType) { return (propertyType.GetInterfaces().Contains(typeof(IList)) || propertyType.GetInterfaces().Contains(typeof(ICollection)) || propertyType.GetInterfaces().Contains(typeof(IDictionary)) || propertyType.IsArray); }
private Type GetLeastGeneralCommonType(Type type1, Type type2) { if (type1.IsInterface) { if (type2.GetInterfaces().Contains(type1)) return type1; if (type2.IsInterface) { if (type1.GetInterfaces().Contains(type2)) return type2; } return typeof(object); } else { if (type2.IsInterface) { if (type1.GetInterfaces().Contains(type2)) return type2; return typeof(object); } Type current = type1; List<Type> types = new List<Type>(); while (current != null) { types.Add(current); current = current.BaseType; } current = type2; while (!types.Contains(current)) { current = current.BaseType; } return current; } }
public override object Resolve(Type jobType) { var instance = _container.TryGetInstance(jobType); // since it fails we can try to get the first interface and request from container if (instance == null && jobType.GetInterfaces().Count() > 0) instance = _container.GetInstance(jobType.GetInterfaces().FirstOrDefault()); return instance; }
public override object ActivateJob(Type jobType) { // this will fail if you do self referencing job queues on a class with an interface: // BackgroundJob.Enqueue(() => this.SendSms(message)); var instance = _container.TryGetInstance(jobType); // since it fails we can try to get the first interface and request from container if (instance==null && jobType.GetInterfaces().Count()>0) instance = _container.GetInstance(jobType.GetInterfaces().FirstOrDefault()); return instance; }
public ITypeBuilder CreateTypeBuilder(Type type) { // Check which ICollection<T> is implemented var interfaceType = (from @interface in new[] {type}.Concat(type.GetInterfaces()) where @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof (ICollection<>) select @interface) .FirstOrDefault(); if (interfaceType == null) { // Check if it is IEnumerable<T> interfaceType = (from @interface in new[] {type}.Concat(type.GetInterfaces()) where @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof (IEnumerable<>) select @interface) .FirstOrDefault(); } if (interfaceType == null) { return null; } var elementType = interfaceType.GetGenericArguments()[0]; // Determine concrete ICollection<T> to instantiate var listType = type.IsInterface ? typeof (List<>).MakeGenericType(elementType) : type; if (!type.IsAssignableFrom(listType)) { return null; } // List must have default constructor if (listType.GetConstructor(Type.EmptyTypes) == null) { return null; } return ((ITypeBuilderFactory) typeof (CollectionBuilderFactory<,>) .MakeGenericType(listType, interfaceType.GetGenericArguments()[0]) .GetConstructor(Type.EmptyTypes) .Invoke(new object[0])).CreateTypeBuilder(type); }
private static IEnumerable<Type> EnumerateGenericIntefaces( Type source, Type genericType, bool includesOwn ) { return ( includesOwn ? new[] { source }.Concat( source.GetInterfaces() ) : source.GetInterfaces() ) .Where( @interface => @interface.GetIsGenericType() && ( genericType.GetIsGenericTypeDefinition() ? @interface.GetGenericTypeDefinition() == genericType : @interface == genericType ) ).Select( @interface => // If source is GenericTypeDefinition, type def is only valid type (i.e. has name) source.GetIsGenericTypeDefinition() ? @interface.GetGenericTypeDefinition() : @interface ); }
private static IEnumerable<Type> GetAllServiceTypesFor(Type t) { if (t == null) { return new List<Type>(); } List<Type> list2 = new List<Type>(t.GetInterfaces()) { t }; List<Type> list = list2; foreach (Type type in t.GetInterfaces()) { list.AddRange(GetAllServiceTypesFor(type)); } return list; }
public ConcurrentAttribute(ConcurrentBehavior behavior, Type resolver) { this.Behavior = behavior; if (behavior == ConcurrentBehavior.Dynamic) { if (resolver.GetInterfaces().Length != 1 || resolver.GetInterfaces()[0] != typeof(IUserDefinedMergeResolver)) { throw new ArgumentException("User defined resolver type missing or not derived from IUserDefinedMergeResolver"); } this.Resolver = resolver; } }
public void Register(IIocBuilder builder, Type type) { if (!type.IsAbstract && type.IsClass) { var itypes = type.GetInterfaces(); if (itypes != null && itypes.Length > 0) { var itype = type.GetInterfaces()[0]; if (itype.IsGenericType && itype.GetGenericTypeDefinition().Equals(typeof(IMessageMapper<>))) { builder.RegisterType(itype, type, LifeTimeScope.Transient, type.FullName); } } } }
private static void AddInterfaceProperties(List <PropertyInfo> properties, System.Type t) { foreach (var intf in t.GetInterfaces()) { var ps = intf.GetProperties(c_BindingFlags); if (null != ps) { properties.AddRange(ps); } } foreach (var intf in t.GetInterfaces()) { AddInterfaceProperties(properties, intf); } }
private static void AddInterfaceMethods(List <MethodInfo> methods, System.Type t) { foreach (var intf in t.GetInterfaces()) { var ms = intf.GetMethods(c_BindingFlags); if (null != ms) { methods.AddRange(ms); } } foreach (var intf in t.GetInterfaces()) { AddInterfaceMethods(methods, intf); } }
/// <summary> /// Check to see if a type implements a named interface. /// </summary> /// <param name="fixtureType">The type to examine</param> /// <param name="interfaceName">The FullName of the interface to check for</param> /// <returns>True if the interface is implemented by the type</returns> public static bool HasInterface(Type fixtureType, string interfaceName) { foreach (Type type in fixtureType.GetInterfaces()) if (type.FullName == interfaceName) return true; return false; }
private void BuildHandlersMap(Type service, Dictionary<MethodInfo, FactoryMethod> map) { if (service == null) { return; } if (service.Equals(typeof(IDisposable))) { var method = service.GetMethods()[0]; map[method] = FactoryMethod.Dispose; return; } var methods = service.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); foreach (var method in methods) { if (IsReleaseMethod(method)) { map[method] = FactoryMethod.Release; continue; } map[method] = FactoryMethod.Resolve; } foreach (var @interface in service.GetInterfaces()) { BuildHandlersMap(@interface, map); } }
private Type DetermineParameterValueType(Type parameterType) { // if the parameter is a generic collection. if (parameterType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(parameterType)) { Type genericEnumerableType = null; if (typeof(IEnumerable<>).IsAssignableFrom(parameterType.GetGenericTypeDefinition())) { genericEnumerableType = parameterType; } else { genericEnumerableType = (from interfaceType in parameterType.GetInterfaces() where interfaceType.IsGenericType where typeof(IEnumerable<>) .IsAssignableFrom(interfaceType.GetGenericTypeDefinition()) select interfaceType).Single(); } return genericEnumerableType.GetGenericArguments().Single(); } else { return parameterType; } }
private static Type FindIEnumerable(Type seqType) { if (seqType == null || seqType == typeof(string)) return null; if (seqType.IsArray) return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); if (seqType.IsGenericType) foreach (var arg in seqType.GetGenericArguments()) { var ienum = typeof(IEnumerable<>).MakeGenericType(arg); if (ienum.IsAssignableFrom(seqType)) return ienum; } var ifaces = seqType.GetInterfaces(); if (ifaces != null) foreach (var iface in ifaces) { var ienum = FindIEnumerable(iface); if (ienum != null) return ienum; } if (seqType.BaseType != null && seqType.BaseType != typeof(object)) return FindIEnumerable(seqType.BaseType); return null; }
private static Type GetEnumerableType(Type type) { return type.GetInterfaces() .Where(intType => intType.IsGenericType && intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) .Select(intType => intType.GetGenericArguments()[0]) .FirstOrDefault(); }
/// <summary> /// Searches for a particular implementation of the given interface type inside of the type. /// This is particularly useful if the interface type is an open type, ie, typeof(IFace{}), /// because this method will then return IFace{} but with appropriate type parameters /// inserted. /// </summary> /// <param name="type">The base type to search for interface</param> /// <param name="interfaceType">The interface type to search for. Can be an open generic /// type.</param> /// <returns>The actual interface type that the type contains, or null if there is no /// implementation of the given interfaceType on type.</returns> public static Type GetInterface(Type type, Type interfaceType) { if (interfaceType.Resolve().IsGenericType && interfaceType.Resolve().IsGenericTypeDefinition == false) { throw new ArgumentException("GetInterface requires that if the interface " + "type is generic, then it must be the generic type definition, not a " + "specific generic type instantiation"); }; while (type != null) { foreach (var iface in type.GetInterfaces()) { if (iface.Resolve().IsGenericType) { if (interfaceType == iface.GetGenericTypeDefinition()) { return iface; } } else if (interfaceType == iface) { return iface; } } type = type.Resolve().BaseType; } return null; }
private static Expression CreateCall(MethodInfo method, ParameterExpression handler, ParameterExpression context, Type handlerType) { if (method.IsGenericMethod) { var handlerParameterType = method.GetParameters()[0].ParameterType; if (handlerParameterType.IsGenericType) { var @interface = handlerType.GetInterfaces().FirstOrDefault( i => i.IsGenericType && i.GetGenericTypeDefinition() == handlerParameterType.GetGenericTypeDefinition()); if (@interface != null) { method = method.MakeGenericMethod(@interface.GetGenericArguments().Single()); } } else { // bind handler as generic type? method = method.MakeGenericMethod(typeof(object)); //Debugger.Break(); } } return Expression.Call(method, handler, context); }
public static Type FindIEnumerable(Type seqType) { if (seqType == null || seqType == typeof(string)) return null; if (seqType.IsArray) return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); if (seqType.IsGenericType) { foreach (Type arg in seqType.GetGenericArguments()) { Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); if (ienum.IsAssignableFrom(seqType)) { return ienum; } } } Type[] ifaces = seqType.GetInterfaces(); if (ifaces != null && ifaces.Length > 0) { foreach (Type iface in ifaces) { Type ienum = FindIEnumerable(iface); if (ienum != null) return ienum; } } if (seqType.BaseType != null && seqType.BaseType != typeof(object)) { return FindIEnumerable(seqType.BaseType); } return null; }
protected override Type GetRowType(Type objectType) { Type type = null; if ((objectType.IsInterface && objectType.IsGenericType) && (objectType.GetGenericTypeDefinition() == typeof(IEnumerable<>))) { type = objectType; } else { foreach (Type type2 in objectType.GetInterfaces()) { if (type2.IsGenericType && (type2.GetGenericTypeDefinition() == typeof(IEnumerable<>))) { type = type2; break; } } } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments[0].IsGenericParameter) { return null; } return genericArguments[0]; }
private static BaseWrapper CreateWrapperFromType(Type type, Type itemType) { BaseWrapper retval = null; if (type.IsArray) { retval = (BaseWrapper)Activator.CreateInstance(typeof(ArrayWrapper<>).MakeGenericType(itemType)); } else { var types = new List<Type>(type.GetInterfaces() .Select(h => h.IsGenericType ? h.GetGenericTypeDefinition() : h)); types.Insert(0, type.IsGenericType ? type.GetGenericTypeDefinition() : type); if (types.Any(i => typeof(IList<>).IsAssignableFrom(i) || typeof(IList).IsAssignableFrom(i))) { retval = new ListWrapper(); } else if (types.Any(y => typeof(ICollection<>).IsAssignableFrom(y))) { retval = (BaseWrapper)Activator.CreateInstance(typeof(CollectionWrapper<>).MakeGenericType(itemType)); } else if (types.Any(i => typeof(IEnumerable<>).IsAssignableFrom(i) || typeof(IEnumerable).IsAssignableFrom(i))) { retval = new ListWrapper(); } else if (retval == null) { //we gave it our best shot, but we couldn't figure out how to deserialize this badboy. throw new MongoException(string.Format("Collection of type {0} cannot be deserialized.", type.FullName)); } } return retval; }
internal static ResourceInfoAttribute GetMostInheritedResourceInterfaceInfo( this IClientTypeResolver client, Type sourceType) { ResourceInfoAttribute sourceTypeResourceInfo; if (client.TryGetResourceInfoForType(sourceType, out sourceTypeResourceInfo)) return sourceTypeResourceInfo; var allResourceInfos = sourceType.GetInterfaces().Select( x => { ResourceInfoAttribute resourceInfo; if (!client.TryGetResourceInfoForType(x, out resourceInfo)) resourceInfo = null; return resourceInfo; }).Where(x => x != null).ToList(); var mostSubtyped = allResourceInfos .FirstOrDefault( x => !allResourceInfos.Any( y => x.InterfaceType != y.InterfaceType && x.InterfaceType.IsAssignableFrom(y.InterfaceType))); return mostSubtyped; }
internal SqlCallInfo(AssemblyInventory inventory, ISerializationTypeInfoProvider serializationTypeInfoProvider, Type interfaceType, ISerializationTypeMappingProvider typeMappingProvider) { if (inventory == null) { throw new ArgumentNullException("inventory"); } if (serializationTypeInfoProvider == null) { throw new ArgumentNullException("serializationTypeInfoProvider"); } Debug.Assert(interfaceType != null); if ((!interfaceType.IsInterface) || (interfaceType.IsGenericTypeDefinition) || (!typeof(IStoredProcedures).IsAssignableFrom(interfaceType))) { throw new ArgumentException("The interface must inherit from IStoredProcedures", "interfaceType"); } this.interfaceType = interfaceType; foreach (Type innerInterface in interfaceType.GetInterfaces()) { if (innerInterface != typeof(IStoredProcedures)) { throw new ArgumentException("The interface cannot inherit from other interfaces then IStoredProcedures", "interfaceType"); } } foreach (MemberInfo memberInfo in interfaceType.GetMembers(BindingFlags.Instance|BindingFlags.Public|BindingFlags.DeclaredOnly)) { MethodInfo methodInfo = memberInfo as MethodInfo; if (methodInfo == null) { throw new ArgumentException("Only methods are supported on the IStoredProcedures interfaces", "interfaceType"); } methods.Add(methodInfo, new SqlCallProcedureInfo(inventory, serializationTypeInfoProvider, methodInfo, typeMappingProvider)); } }
public ArrayList bases(Type c) { ArrayList supers = new ArrayList(); if(c.IsInterface) supers.Add(Type.GetType("System.Object")); else if(c.BaseType != null) supers.Add(c.BaseType); Type[] interfaces = c.GetInterfaces(); for(int i=0;i<interfaces.Length;i++) { Type inter = interfaces[i]; bool placed = false; for(int p=0;!placed && p<supers.Count;p++) { Type s = (Type)supers[p]; if(s.IsAssignableFrom(inter)) { supers[p] = inter; placed = true; } } if(!placed) supers.Add(inter); } for(int p=0;p<supers.Count;p++) supers[p] = ((Type)supers[p]).ToString(); return supers; }
public static void CheckForInterface(Type type, Type interfaceType) { if (type == null || interfaceType == null) return; if (Array.IndexOf<Type>(type.GetInterfaces(), interfaceType) == -1) throw new System.Configuration.ConfigurationErrorsException("The type " + type.AssemblyQualifiedName + " must implement " + interfaceType.AssemblyQualifiedName); }
/// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig" /> that should be applied during binding.</param> /// <param name="blackList">Blacklisted property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { Type genericType = null; if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure it has a generic type if (modelType.IsGenericType()) { genericType = modelType.GetGenericArguments().FirstOrDefault(); } else { var implementingIEnumerableType = modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault( i => i.GetGenericTypeDefinition() == typeof (IEnumerable<>)); genericType = implementingIEnumerableType == null ? null : implementingIEnumerableType.GetGenericArguments().FirstOrDefault(); } if (genericType == null) { throw new ArgumentException("When modelType is an enumerable it must specify the type", "modelType"); } } var bindingContext = CreateBindingContext(context, modelType, instance, configuration, blackList, genericType); var bodyDeserializedModel = DeserializeRequestBody(bindingContext); return (instance as IEnumerable<string>) ?? bodyDeserializedModel; }
public override bool ShouldMap(Type type) { return type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>)); }
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { WebServiceHost2Ex webServiceHost2Ex = new WebServiceHost2Ex(serviceType, baseAddresses); //new code Uri[] defaultAddresses = new Uri[1]; defaultAddresses[0] = baseAddresses[0]; // Bind up the JSONP extension CustomBinding cb = new CustomBinding(new WebHttpBinding()); cb.Name = "JSONPBinding"; // Replace the current MessageEncodingBindingElement with the JSONP element var currentEncoder = cb.Elements.Find<MessageEncodingBindingElement>(); if (currentEncoder != default(MessageEncodingBindingElement)) { cb.Elements.Remove(currentEncoder); cb.Elements.Insert(0, new JSONPBindingElement()); } webServiceHost2Ex.AddServiceEndpoint(serviceType.GetInterfaces()[0], cb, defaultAddresses[0]); return webServiceHost2Ex; }
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { for (int i = 0; i < importedAssets.Length; i++) { System.Type t = AssetDatabase.GetMainAssetTypeAtPath(importedAssets[i]); if (t != null? !t.GetInterfaces().Contains(typeof(IOnPostProcessImportAssetCallback)):true) { continue; } object[] assets = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(importedAssets[i]); if (assets != null) { for (int ii = 0; ii < assets.Length; ii++) { IOnPostProcessImportAssetCallback postprocess = (IOnPostProcessImportAssetCallback)assets[ii]; if (postprocess != null) { postprocess.OnAssetImported(); } } } } for (int i = 0; i < movedAssets.Length; i++) { System.Type t = AssetDatabase.GetMainAssetTypeAtPath(movedAssets[i]); if (t != null ? !t.GetInterfaces().Contains(typeof(IOnPostProcessMoveAssetCallback)) : true) { continue; } object[] assets = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(importedAssets[i]); if (assets != null) { for (int ii = 0; ii < assets.Length; ii++) { IOnPostProcessMoveAssetCallback postprocess = (IOnPostProcessMoveAssetCallback)assets[ii]; if (postprocess != null) { postprocess.OnAssetMoved(); } } } } }
private static UnityEditor.AssetDeleteResult OnWillDeleteAsset(string assetToDelete, UnityEditor.RemoveAssetOptions removeAssetOptions) { System.Type t = AssetDatabase.GetMainAssetTypeAtPath(assetToDelete); if (t != null ? !t.GetInterfaces().Contains(typeof(IOnWillDeleteAssetCallback)) : true) { return(UnityEditor.AssetDeleteResult.DidNotDelete); } object[] assets = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(assetToDelete); if (assets != null) { for (int ii = 0; ii < assets.Length; ii++) { IOnWillDeleteAssetCallback onWillDelete = (IOnWillDeleteAssetCallback)assets[ii]; if (onWillDelete != null) { onWillDelete.OnWillDelete(); } } } return(UnityEditor.AssetDeleteResult.DidNotDelete); }
public static System.Type[] GetDependencies(System.Type type) { List <System.Type> dependencies = new List <System.Type>(); var interfaces = type.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { var current = interfaces[i]; if (current == null || !current.IsGenericType) { continue; } if (current.GetGenericTypeDefinition() != typeof(IManagerDependency <>)) { continue; } dependencies.Add(current.GetGenericArguments()[0]); } return(dependencies.ToArray()); }
internal static MethodInfo GetInterfaceMethod(System.Type interfaceType, string methodName) { MethodInfo info = null; string str = string.Empty; string name = string.Empty; if (methodName.LastIndexOf('.') > 0) { str = methodName.Substring(0, methodName.LastIndexOf('.')); name = methodName.Substring(methodName.LastIndexOf('.') + 1); } if (!string.IsNullOrEmpty(str)) { foreach (System.Type type in interfaceType.GetInterfaces()) { if (string.Compare(type.FullName, str, StringComparison.Ordinal) == 0) { return(type.GetMethod(name)); } } return(info); } return(interfaceType.GetMethod(methodName)); }
public static bool InheritsFrom(this System.Type type, System.Type baseType) { if (baseType.IsAssignableFrom(type)) { return(true); } if (type.IsInterface && !baseType.IsInterface) { return(false); } if (baseType.IsInterface) { return(Enumerable.Contains(type.GetInterfaces(), baseType)); } for (System.Type currentType = type; currentType != null; currentType = currentType.BaseType) { if (currentType == baseType || baseType.IsGenericTypeDefinition && currentType.IsGenericType && currentType.GetGenericTypeDefinition() == baseType) { return(true); } } return(false); }
static string[] OnWillSaveAssets(string[] paths) { for (int i = 0; i < paths.Length; i++) { System.Type t = AssetDatabase.GetMainAssetTypeAtPath(paths[i]); if (t != null ? !t.GetInterfaces().Contains(typeof(IOnWillSaveAssetCallback)) : true) { continue; } object[] assets = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(paths[i]); if (assets != null) { for (int ii = 0; ii < assets.Length; ii++) { IOnWillSaveAssetCallback postprocess = (IOnWillSaveAssetCallback)assets[ii]; if (postprocess != null) { postprocess.OnWillSave(); } } } } return(paths); }
private static MethodInfo GetMethodFromInterface(System.Type type, string methodName, System.Type[] parametersTypes) { const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly; if (type == null) { return(null); } MethodInfo method = type.GetMethod(methodName, flags, null, parametersTypes, null); if (method == null) { System.Type[] interfaces = type.GetInterfaces(); foreach (var @interface in interfaces) { method = GetMethodFromInterface(@interface, methodName, parametersTypes); if (method != null) { return(method); } } } return(method); }
/// <summary> /// Gets the public name for the specified type /// </summary> public static String GetTypeName(System.Type type) { if (type.IsClass) { type = type.GetInterfaces().FirstOrDefault(iface => iface.GetGenericArguments().Length == 0 && iface.Namespace == type.Namespace && type.Assembly.GetName().Name.StartsWith(iface.Assembly.GetName().Name) && type.Assembly.GetName().Name != iface.Assembly.GetName().Name) ?? type; } if (type == typeof(void)) { return("void"); } else if (Nullable.GetUnderlyingType(type) == null) { return(type.Name); } else { return(Nullable.GetUnderlyingType(type).Name + "?"); } }
/// <summary> 获取当前类型的 TypeCodes 值 /// </summary> private TypeCodes GetTypeCodes() { if (IsNullable) //可空值类型 { return(NullableUnderlyingType.GetTypeCodes()); } if (Type.IsEnum) { return(blqw.TypeCodes.Enum); } if (IsMakeGenericType && Type.Name.StartsWith("<>f__AnonymousType")) //判断匿名类 { return(TypeCodes.AnonymousType); } var interfaces = Type.GetInterfaces(); var length = interfaces.Length; for (int i = 0; i < length; i++) { var inf = interfaces[i]; if (inf.IsGenericTypeDefinition) { } else if (inf.IsGenericType) { inf = inf.GetGenericTypeDefinition(); } else { continue; } if (inf == typeof(IList <>)) { return(TypeCodes.IListT); } else if (inf == typeof(IDictionary <,>)) { return(TypeCodes.IDictionaryT); } } if (TypeCode == TypeCode.Object) { if (Type == typeof(TimeSpan)) { return(TypeCodes.TimeSpan); } else if (Type == typeof(Guid)) { return(TypeCodes.Guid); } else if (Type == typeof(System.Text.StringBuilder)) { return(TypeCodes.StringBuilder); } else if (Type == typeof(System.Data.DataSet)) { return(TypeCodes.DataSet); } else if (Type == typeof(System.Data.DataTable)) { return(TypeCodes.DataTable); } else if (Type == typeof(System.Data.DataView)) { return(TypeCodes.DataView); } else if (Type == typeof(IntPtr)) { return(TypeCodes.IntPtr); } else if (Type == typeof(UIntPtr)) { return(TypeCodes.UIntPtr); } else if (Type == typeof(System.Xml.XmlDocument)) { return(TypeCodes.Xml); } else if (typeof(System.Collections.IList).IsAssignableFrom(Type)) { return(TypeCodes.IList); } else if (typeof(System.Collections.IDictionary).IsAssignableFrom(Type)) { return(TypeCodes.IDictionary); } else if (typeof(System.Data.Common.DbDataReader).IsAssignableFrom(Type)) { return(TypeCodes.DbDataReader); } else if (typeof(System.Data.Common.DbParameter).IsAssignableFrom(Type)) { return(TypeCodes.DbParameter); } else if (typeof(Type).IsAssignableFrom(Type)) { return(TypeCodes.Type); } } return((TypeCodes)TypeCode); }
private static bool IsInterfaceImplemented(System.Type derivedType, System.Type interfaceType) => (-1 != Array.IndexOf <System.Type>(derivedType.GetInterfaces(), interfaceType));
static public object Reconstitute(System.Type type, string data) { object returnData = null; if (type == typeof(String)) { returnData = (string)data; } else if (type == typeof(Boolean)) { returnData = Convert.ToBoolean(data); } else if (type == typeof(SByte)) { returnData = Convert.ToSByte(data); } else if (type == typeof(Int16)) { returnData = Convert.ToInt16(data); } else if (type == typeof(Int32)) { returnData = Convert.ToInt32(data); } else if (type == typeof(Int64)) { returnData = Convert.ToInt64(data); } else if (type == typeof(Byte)) { returnData = Convert.ToByte(data); } else if (type == typeof(UInt16)) { returnData = Convert.ToUInt16(data); } else if (type == typeof(UInt32)) { returnData = Convert.ToUInt32(data); } else if (type == typeof(UInt64)) { returnData = Convert.ToUInt64(data); } else if (type == typeof(Decimal)) { returnData = Convert.ToDecimal(data); } else if (type == typeof(Guid)) { returnData = new Guid(data); } else if (type == typeof(Single)) { returnData = Convert.ToSingle(data); } else if (type == typeof(Double)) { returnData = Convert.ToDouble(data); } else if (type == typeof(DateTime)) { returnData = DateTime.Parse(data); } else if (type == typeof(TimeSpan)) { returnData = TimeSpan.Parse(data); } else { LoadCustomSerializers(); ITypeSerializer cts = _serializers[type] as ITypeSerializer; if (cts != null) { returnData = cts.Reconstitute(data); } else { bool found = false; foreach (ITypeSerializer ts in _serializers.Values) { if (ts.DataType.IsClass) { if (type.IsSubclassOf(ts.DataType)) { returnData = ts.Reconstitute(data); found = true; } } else if (ts.DataType.IsInterface) { Type[] ifaces = type.GetInterfaces(); foreach (Type iface in ifaces) { if (iface == ts.DataType) { returnData = ts.Reconstitute(data); found = true; break; } } } if (found) { break; } } if (!found) { throw new Exception("Unserializable type: " + data.GetType().FullName); } } } return(returnData); }
/// <summary> /// 判断当前 <see cref="System.Type"/> 指示的类型是否实现或(等价于)某个 <see cref="System.Type"/> 指示的接口。 /// </summary> /// <param name="_this">当前 <see cref="System.Type"/> 对象。</param> /// <param name="c">用于比较的 <see cref="System.Type"/> 类型对象,表示一个接口类型。</param> /// <returns>如果当前类型等价或继承与指定的接口类型,则返回 true,否则返回 false。</returns> public static bool IsImplementOf(this System.Type _this, System.Type c) { return(_this == c || _this.GetInterfaces().Contains(c)); }
private void WriteClassOrStruct(StreamWriter s, System.Type t, Kind k) { WriteAttributes(t, s); s.Write("public "); if (t.IsAbstract) { s.Write("abstract "); } s.Write(k.ToString().ToLower()); s.Write(" "); s.Write(GetTypeName(t, false)); List <string> implements = new List <string>(); if (t.BaseType != null && t.BaseType != typeof(object) && t.BaseType != typeof(ValueType) && t.BaseType.IsPublic) { implements.Add(GetTypeName(t.BaseType)); } foreach (System.Type interfaceType in t.GetInterfaces()) { if (interfaceType.Name.StartsWith("_") || t.BaseType.IsPublic) { // Ignore the special IL classes like _Exception and _Attribute, // the class will still inherit from System.Exception or System.Attribute continue; } implements.Add(GetTypeName(interfaceType)); } if (implements.Count > 0) { s.Write(" : "); bool first = true; foreach (string implement in implements) { if (first) { first = false; } else { s.Write(", "); } s.Write(implement); } } s.Write(" {\n"); s.WriteLine("\t// Mock data:"); s.WriteLine("\tprivate Dictionary<string, int> mFunctionCallCounts;"); s.WriteLine("\tpublic Dictionary<string, int> functionCallCounts {"); s.WriteLine("\t\tget { "); s.WriteLine("\t\t\tif(mFunctionCallCounts == null) {"); s.WriteLine("\t\t\t\tmFunctionCallCounts = new Dictionary<string, int>();"); s.WriteLine("\t\t\t}"); s.WriteLine("\t\t\treturn mFunctionCallCounts;"); s.WriteLine("\t\t}"); s.WriteLine("\t}"); WriteMemberFunctions(s, t); s.WriteLine("}"); }
internal static FieldInfo[] GetBindableMembers(TypeInfo typeInfo) { /* * var rpcInterface = GetRpcInterface(); * if (rpcInterface != null) * { * var rpcInterfaceMap = typeInfo.GetInterfaceMap(rpcInterface); * //members = rpcInterfaceMap.TargetMethods; * } */ Type baseType; if (ReflectionSerializerVerifier.HasRdExtAttribute(typeInfo)) { baseType = typeof(RdExtReflectionBindableBase); } else if (ReflectionSerializerVerifier.HasRdModelAttribute(typeInfo)) { baseType = typeof(RdReflectionBindableBase); } else { baseType = typeof(RdBindableBase); } bool isRdExtImpl = baseType == typeof(RdExtReflectionBindableBase) && !typeInfo.GetInterfaces().Contains(typeof(IProxyTypeMarker)); bool isRdRpcInterface = typeInfo.IsInterface; // can be specified in RdExt // && typeInfo.GetCustomAttribute<RdRpcAttribute>() != null; var fields = GetFields(typeInfo, baseType); var list = new List <FieldInfo>(); foreach (var mi in fields) { if (typeof(RdExtReflectionBindableBase).IsAssignableFrom(mi.FieldType)) { continue; } if ( mi.MemberType == MemberTypes.Field && (mi.DeclaringType != null && !mi.DeclaringType.GetTypeInfo().IsAssignableFrom(baseType)) && mi.GetCustomAttribute <NonSerializedAttribute>() == null && // arbitrary data is allowed in RdExt implementations since they don't have to be serializable !(isRdExtImpl && ReflectionSerializerVerifier.IsScalar(ReflectionSerializerVerifier.GetImplementingType(mi.FieldType.GetTypeInfo()))) ) { list.Add(mi); } else if (isRdRpcInterface) { throw new Exception($"Invalid member in RdRpc interface: {typeInfo.ToString(true)}.{mi.Name}"); } } return(list.ToArray()); }
private static IEnumerable <TypeReference> GetAllInterfacesRecursive(TypeReference typeDefinition) { return(typeDefinition .WrapAsEnumerable() .Concat(typeDefinition.GetInterfaces().SelectMany(GetAllInterfacesRecursive))); }
private static Dictionary <System.Type, Dictionary <MethodInfo, MethodInfo> > BuildInterfacesMap(System.Type type) { return(type.GetInterfaces() .Distinct() .ToDictionary(i => i, i => ToDictionary(type.GetInterfaceMap(i)))); }
/// <summary> /// Получить бизнессерве /// </summary> /// <param name="dataObjectType">для объекта типа</param> /// <param name="dsevent">событие</param> /// <returns></returns> static public BusinessServer[] GetBusinessServer(System.Type dataObjectType, DataServiceObjectEvents dsevent, IDataService ds) { //2011-08-04 Братчиков: кешируем с учётом разных строк соединения. Это нужно для того чтобы не переписывать чужому бизнес-серверу датасервис string key = dataObjectType.FullName + "." + dsevent + "." + (ds != null? (ds.CustomizationString ?? "salt"):"tlas").GetHashCode(); lock (cache) { if (cache.ContainsKey(key)) { BusinessServer[] ret_bs = (BusinessServer[])cache[key]; foreach (BusinessServer bsi in ret_bs) { bsi.DataService = ds; } return(ret_bs); } ArrayList bss = new ArrayList(); bool needSort = false; while (dataObjectType != typeof(DataObject) && dataObjectType != typeof(object)) { // TODO: разобраться с логикой выполнения и привести в соответствие со статьёй http://storm:3013/Otrabotka-polzovatelskih-operacii-v-processe-raboty-servisa-dannyh-integraciya-s-biznes-serverom.ashx. //получим сначала бизнес-сервера у самого класса (не может быть больше одного) ArrayList atrs = new ArrayList(dataObjectType.GetCustomAttributes(typeof(BusinessServerAttribute), false)); //добавим бизнес-сервера, которые достались от интерфейсов Type[] interfaces = dataObjectType.GetInterfaces(); List <Type> baseInterfaces = new List <Type>(); if (dataObjectType.BaseType != null) { baseInterfaces.AddRange(dataObjectType.BaseType.GetInterfaces()); } foreach (Type interf in interfaces) { if (!baseInterfaces.Contains(interf)) { atrs.AddRange(interf.GetCustomAttributes(typeof(BusinessServerAttribute), false)); } } //создадим инстанции бизнес-серверов и добавим в итоговый массив foreach (BusinessServerAttribute atr in atrs) { if ((dsevent & atr.ServerEvents) == dsevent) { BusinessServer bs = (BusinessServer)Activator.CreateInstance(atr.BusinessServerType); bs.DataService = ds; bs.SetType(dataObjectType); bss.Insert(0, bs); if (atr.Order != 0) { bs.Order = atr.Order; needSort = true; } } } dataObjectType = dataObjectType.BaseType; } //пересортируем бизнессерверы if (needSort) { //Получим отсортированный список, в котором будет упорядоченная коллекция с допустимыми одинаковыми ключами //bss.Sort(new BusinesServerComparer()); ArrayList sortedArList = new ArrayList(); SortedList sl = new SortedList(); foreach (BusinessServer bs in bss) { if (!sl.ContainsKey(bs.Order)) { sl.Add(bs.Order, new ArrayList()); } ((ArrayList)sl[bs.Order]).Add(bs); } foreach (DictionaryEntry entry in sl) { ArrayList arl = (ArrayList)entry.Value; sortedArList.AddRange(arl); } bss = sortedArList; } BusinessServer[] res = (BusinessServer[])bss.ToArray(typeof(BusinessServer)); cache.Add(key, res); return(res); } }
public TypeInfo CreateProxyType(System.Type baseType, IReadOnlyCollection <System.Type> baseInterfaces) { var typeName = $"{baseType.Name}Proxy"; var assemblyName = $"{typeName}Assembly"; var moduleName = $"{typeName}Module"; var name = new AssemblyName(assemblyName); var assemblyBuilder = ProxyAssemblyBuilder.DefineDynamicAssembly(AppDomain.CurrentDomain, name); var moduleBuilder = ProxyAssemblyBuilder.DefineDynamicModule(assemblyBuilder, moduleName); const TypeAttributes typeAttributes = TypeAttributes.AutoClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.BeforeFieldInit; var interfaces = new HashSet <System.Type> { // Add the ISerializable interface so that it can be implemented typeof(ISerializable) }; interfaces.UnionWith(baseInterfaces); interfaces.UnionWith(baseInterfaces.SelectMany(i => i.GetInterfaces())); interfaces.UnionWith(baseType.GetInterfaces()); // Use the object as the base type // since we're not inheriting from any class type var parentType = baseType; if (baseType.IsInterface) { parentType = typeof(object); interfaces.Add(baseType); } var typeBuilder = moduleBuilder.DefineType(typeName, typeAttributes, parentType, interfaces.ToArray()); var lazyInitializerField = typeBuilder.DefineField("__lazyInitializer", LazyInitializerType, FieldAttributes.Private); var proxyInfoField = typeBuilder.DefineField("__proxyInfo", typeof(NHibernateProxyFactoryInfo), FieldAttributes.Private); ImplementConstructor(typeBuilder, parentType, lazyInitializerField, proxyInfoField); // Provide a custom implementation of ISerializable // instead of redirecting it back to the interceptor foreach (var method in ProxyFactory.GetProxiableMethods(baseType, interfaces.Except(new[] { typeof(ISerializable) }))) { CreateProxiedMethod(typeBuilder, method, lazyInitializerField); } // Make the proxy serializable var serializableConstructor = typeof(SerializableAttribute).GetConstructor(System.Type.EmptyTypes); var customAttributeBuilder = new CustomAttributeBuilder(serializableConstructor, Array.Empty <object>()); typeBuilder.SetCustomAttribute(customAttributeBuilder); ImplementDeserializationConstructor(typeBuilder); ImplementGetObjectData(typeBuilder, proxyInfoField, lazyInitializerField); var proxyType = typeBuilder.CreateTypeInfo(); ProxyAssemblyBuilder.Save(assemblyBuilder); return(proxyType); }
public static Dictionary <K, V> TestCommonToObject <K, V>(Stream stream, bool isLoadAll = false, UnityEngine.MonoBehaviour loadAllCortine = null, int maxAsyncReadCnt = 500) where V : class { if (stream == null) { return(null); } ConfigFileHeader header = new ConfigFileHeader(); if (!header.LoadFromStream(stream) || !header.IsVaild) { return(null); } // 读取索引 stream.Seek(header.indexOffset, SeekOrigin.Begin); // 读取类型(之前已经获取到了) ConfigValueType valueType = (ConfigValueType)stream.ReadByte(); Dictionary <K, V> maps = null; switch (valueType) { case ConfigValueType.cvObject: { for (uint i = 0; i < header.Count; ++i) { ConfigBase <K> config = Activator.CreateInstance <V>() as ConfigBase <K>; config.stream = stream; K key = config.ReadKey(); config.dataOffset = FilePathMgr.Instance.ReadLong(stream); if (maps == null) { maps = new Dictionary <K, V>((int)header.Count); } maps[key] = config as V; } break; } case ConfigValueType.cvList: { System.Type t = typeof(V); // 这里有数组分配,不要频繁使用TestCommonToObject var interfaces = t.GetInterfaces(); if (interfaces == null || interfaces.Length <= 0) { return(null); } var inter = interfaces[0]; if (inter == null) { return(null); } for (uint i = 0; i < header.Count; ++i) { ConfigBase <K> config = Activator.CreateInstance(inter) as ConfigBase <K>; config.stream = stream; K key = config.ReadKey(); long dataOffset = FilePathMgr.Instance.ReadLong(stream); config.dataOffset = dataOffset; int listCnt = FilePathMgr.Instance.ReadInt(stream); if (maps == null) { maps = new Dictionary <K, V>((int)header.Count); } V vs = Activator.CreateInstance <V>(); maps[key] = vs; IList list = vs as IList; list.Add(config); for (int j = 1; j < listCnt; ++j) { config = Activator.CreateInstance(inter) as ConfigBase <K>; config.stream = stream; config.dataOffset = dataOffset; list.Add(config); } } break; } default: return(null); } if (isLoadAll && maps != null && maps.Count > 0) { StartLoadAllCortine(maps, loadAllCortine, valueType, null, maxAsyncReadCnt); } return(maps); }
private static bool ContainsInterface <T>(System.Type target) { return(target.GetInterfaces().Contains(typeof(T))); }
public TypeInfo CreateProxyType(System.Type baseType, IReadOnlyCollection <System.Type> baseInterfaces) { System.Type interfaceType = null; if (baseType == typeof(object)) { // Mapping option "proxy" allows to ask for using an interface, which switches the base type to object // and adds the interface to base interfaces set. // Avoids using object for naming the proxy, as otherwise all entities using the "proxy" option for // specifying an interface would have their proxies sharing the same full name. interfaceType = baseInterfaces.FirstOrDefault(i => i != typeof(INHibernateProxy)); } var typeName = $"{(interfaceType ?? baseType).Name}Proxy"; var assemblyName = $"{typeName}Assembly"; var moduleName = $"{typeName}Module"; var name = new AssemblyName(assemblyName); var assemblyBuilder = ProxyBuilderHelper.DefineDynamicAssembly(AppDomain.CurrentDomain, name); var moduleBuilder = ProxyBuilderHelper.DefineDynamicModule(assemblyBuilder, moduleName); const TypeAttributes typeAttributes = TypeAttributes.AutoClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.BeforeFieldInit; var interfaces = new HashSet <System.Type> { // Add the ISerializable interface so that it can be implemented typeof(ISerializable) }; interfaces.UnionWith(baseInterfaces); interfaces.UnionWith(baseInterfaces.SelectMany(i => i.GetInterfaces())); interfaces.UnionWith(baseType.GetInterfaces()); // Use the object as the base type // since we're not inheriting from any class type var parentType = baseType; if (baseType.IsInterface) { parentType = typeof(object); interfaces.Add(baseType); } #if NETFX || NETCOREAPP2_0 var assemblyNamesToIgnoreAccessCheck = new[] { baseType } .Concat(interfaces).Where(i => !i.IsVisible) .Select(i => i.Assembly.GetName().Name) .Distinct(); foreach (var a in assemblyNamesToIgnoreAccessCheck) { ProxyBuilderHelper.GenerateInstanceOfIgnoresAccessChecksToAttribute(assemblyBuilder, a); } #else interfaces.RemoveWhere(i => !i.IsVisible); #endif var typeBuilder = moduleBuilder.DefineType(typeName, typeAttributes, parentType, interfaces.ToArray()); var lazyInitializerField = typeBuilder.DefineField("__lazyInitializer", LazyInitializerType, FieldAttributes.Private); var proxyInfoField = typeBuilder.DefineField("__proxyInfo", typeof(NHibernateProxyFactoryInfo), FieldAttributes.Private); ImplementConstructor(typeBuilder, parentType, lazyInitializerField, proxyInfoField); // Provide a custom implementation of ISerializable instead of redirecting it back to the interceptor foreach (var method in ProxyBuilderHelper.GetProxiableMethods(baseType, interfaces.Except(new[] { typeof(ISerializable) }))) { CreateProxiedMethod(typeBuilder, method, lazyInitializerField, parentType); } ProxyBuilderHelper.MakeProxySerializable(typeBuilder); ImplementDeserializationConstructor(typeBuilder, parentType); ImplementGetObjectData(typeBuilder, proxyInfoField, lazyInitializerField); var proxyType = typeBuilder.CreateTypeInfo(); ProxyBuilderHelper.Save(assemblyBuilder); return(proxyType); }
TypeReference InferType(IReferenceMap referenceMap, Type type) { type = type ?? throw new ArgumentNullException(nameof(type)); var classAttribute = ReflectionUtils.GetClassAttribute(type); if (classAttribute != null) { return(new TypeReference(classAttribute.FullyQualifiedName)); } var enumAttribute = type.GetCustomAttribute <JsiiEnumAttribute>(); if (enumAttribute != null) { return(new TypeReference(enumAttribute.FullyQualifiedName)); } var interfaceAttribute = type.GetCustomAttribute <JsiiInterfaceAttribute>(); if (interfaceAttribute != null) { return(new TypeReference(interfaceAttribute.FullyQualifiedName)); } var structAttribute = type.GetCustomAttribute <JsiiByValueAttribute>(); if (structAttribute != null) { return(new TypeReference(structAttribute.FullyQualifiedName)); } if (typeof(string).IsAssignableFrom(type)) { return(new TypeReference(primitive: PrimitiveType.String)); } if (typeof(bool).IsAssignableFrom(type)) { return(new TypeReference(primitive: PrimitiveType.Boolean)); } if (IsNumeric(type)) { return(new TypeReference(primitive: PrimitiveType.Number)); } if (typeof(DateTime).IsAssignableFrom(type)) { return(new TypeReference(primitive: PrimitiveType.Date)); } if (typeof(JObject).IsAssignableFrom(type) || typeof(JArray).IsAssignableFrom(type)) { return(new TypeReference(primitive: PrimitiveType.Json)); } if (type.IsArray) { return(new TypeReference ( collection: new CollectionTypeReference ( kind: CollectionKind.Array, elementType: typeof(Object) == type.GetElementType() ? new TypeReference(primitive: PrimitiveType.Any) : InferType(referenceMap, type.GetElementType() !) ) )); } Type dictionaryInterface = type.GetInterfaces() .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary <,>)); if (dictionaryInterface != null) { if (!typeof(string).IsAssignableFrom(dictionaryInterface.GetGenericArguments()[0])) { throw new ArgumentException("All dictionaries must have string keys", nameof(type)); } Type elementType = dictionaryInterface.GetGenericArguments()[1]; return(new TypeReference ( collection: new CollectionTypeReference ( kind: CollectionKind.Map, elementType: typeof(Object) == elementType ? new TypeReference(primitive: PrimitiveType.Any) : InferType(referenceMap, elementType) ) )); } throw new ArgumentException($"Could not infer JSII type for .NET type '{type.Name}'", nameof(type)); }
public Type(System.Type type) { if (type.FullName == "System.Array") { Namespace = "System"; Name = "Array"; Kind = TypeIndexKind.GenericDefinition; GenericParams.Add(new TypeIndex("T", TypeIndexKind.GenericParam)); } else { var ti = FromSystemType(type); if (string.IsNullOrEmpty(ti.Namespace)) { return; } Namespace = ti.Namespace; Name = ti.Name; Kind = ti.Kind; GenericParams = ti.GenericParams; } var ns = GetNamespace(); if (type.IsNested) { var names = Name.Split('.'); var ptype = ns.Types[names[0]]; int i = 1; for (; i < names.Length - 1; i++) { ptype = ptype.Types[names[i]]; } Owner = ptype; Name = names[i]; if (ptype.Types.ContainsKey(Name)) { if (ptype.Types[Name].Kind == TypeIndexKind.General) { ptype.Types.Remove(Name); } else { return; } } ptype.Types.Add(this); } else { if (ns.Types.ContainsKey(Name)) { if (ns.Types[Name].Kind == TypeIndexKind.General) { ns.Types.Remove(Name); } else { return; } } ns.Types.Add(this); } if (type.BaseType != null) { BaseTypes.Add(FromSystemType(type.BaseType)); } var itypes = type.GetInterfaces().ToList(); for (int i = itypes.Count - 1; i >= 0; i--) { for (int j = 0; j < i; j++) { if (itypes[i].IsAssignableFrom(itypes[j])) { itypes.RemoveAt(i); break; } } } foreach (var it in itypes) { BaseTypes.Add(FromSystemType(it)); } foreach (var field in type.GetFields()) { Fields.Add(new Field(field, _type_int)); } if (!type.IsEnum) { foreach (var field in type.GetFields()) { Fields.Add(new Field(field)); } foreach (var property in type.GetProperties()) { Properties.Add(new Property(property)); } foreach (var @event in type.GetEvents()) { Events.Add(new Event(@event)); } var inits = type.GetConstructors().Where(m => !m.IsStatic); Methods.Add(new Method(inits)); //去除基类已定义的函数 var imethodnames = type.GetInterfaces() .SelectMany(t => t.GetMethods()) .Select(m => m.Name) .Distinct(); var methodnames = Properties.SelectMany(p => p.Value.Methodnames) .Union(Events.SelectMany(e => e.Value.Methodnames)) .Union(imethodnames); if (type.BaseType != null) { var bmethodnames = type.BaseType .GetMethods() .Select(m => m.Name) .Distinct(); methodnames = methodnames.Union(bmethodnames); } var methods = type.GetMethods() .Where(m => !(m.IsStatic && m.Name.StartsWith("op_")) && !m.Name.Contains(".")) .GroupBy(m => m.Name) .Where(g => !methodnames.Contains(g.Key)); foreach (var g in methods) { Methods.Add(new Method(g)); } if (Kind == TypeIndexKind.GenericDefinition) { var bti = new TypeIndex("typing", "Generic", TypeIndexKind.GenericDefinition); foreach (var p in GenericParams) { bti.GenericParams.Add(p); } BaseTypes.Add(bti); } var prop = Properties.Select(p => p.Value).FirstOrDefault(p => p.IsIndex); if (prop != null) { var bti = new TypeIndex("typing", "Iterable", TypeIndexKind.GenericDefinition); bti.GenericParams.Add(prop.TypeIndex); BaseTypes.Add(bti); } else if (type.FullName == "System.Array") { var bti = new TypeIndex("typing", "Iterable", TypeIndexKind.GenericDefinition); bti.GenericParams.Add(new TypeIndex("T", TypeIndexKind.GenericParam)); BaseTypes.Add(bti); } if (BaseTypes.Count > 1 && BaseTypes[0].Equals(Object)) { BaseTypes.RemoveAt(0); } //去除基类已定义的事件 var eventnames = type.GetInterfaces() .SelectMany(i => i.GetEvents()) .Select(e => e.Name); if (type.BaseType != null) { eventnames = type.BaseType .GetEvents() .Select(e => e.Name) .Union(eventnames); } foreach (var name in eventnames.Distinct()) { Events.Remove(name); } //去除基类已定义的属性 var propnames = type.GetInterfaces() .SelectMany(i => i.GetProperties()) .Select(p => p.Name); if (type.BaseType != null) { propnames = type.BaseType .GetProperties() .Select(p => p.Name) .Union(propnames); } foreach (var name in propnames.Distinct()) { Properties.Remove(name); } } }
protected static bool IsSameOrSubClassOrImplementInterface(System.Type p_potentialDescendant, System.Type p_potentialBase) { if (p_potentialBase != null && p_potentialDescendant != null) { bool v_sucess = p_potentialBase.IsAssignableFrom(p_potentialDescendant) || (new List <System.Type>(p_potentialDescendant.GetInterfaces())).Contains(p_potentialBase); if (!v_sucess) { v_sucess = IsSameOrSubclass(p_potentialDescendant, p_potentialBase); } return(v_sucess); } return(false); }
public void Assign(UnityELEvaluator context, object value) { object host = Host.Evaluate(context); if (host == null) { throw new ParserException(this, $"Did not resolve host object: {Host}"); } System.Type hostType = host.GetType(); object key = Children[0].Evaluate(context); System.Type keyType = key?.GetType(); // If the key is a string, we need to see if there is a property on the host that matches if (key is string) { PropertyInfo info = hostType.GetProperty((string)key); if (info != null) { if (!info.CanWrite || info.SetMethod == null || info.SetMethod.IsPrivate) { throw new ParserException(this, $"Property: {key} on type: {hostType} is read only"); } System.Type propertyType = info.PropertyType; object coercedValue = TypeCoercer.CoerceToType(propertyType, this, value); info.SetValue(host, coercedValue); return; } } // Otherwise inspect the host to determine what to do if (host is IDictionary) { // See if there is a generic type information Type genericDictionaryType = typeof(IDictionary <,>); MethodInfo assignGenericDictionaryMethod = this.GetType().GetMethod("AssignGenericDictionary", BindingFlags.Instance | BindingFlags.NonPublic); foreach (Type type in hostType.GetInterfaces()) { if (type.IsGenericType && type.GetGenericTypeDefinition() == genericDictionaryType) { assignGenericDictionaryMethod.MakeGenericMethod(type.GetGenericArguments()) .Invoke(this, new object[] { host, key, value }); return; } } // Otheriwse, just use IDictionary IDictionary dictionary = (IDictionary)host; dictionary[key] = value; } else if (host is IList) { int i = TypeCoercer.CoerceToType <int>(this, key); // See if there is a generic type information available Type genericListType = typeof(IList <>); MethodInfo assignGenericListMethod = this.GetType().GetMethod("AssignGenericList", BindingFlags.Instance | BindingFlags.NonPublic); foreach (Type type in hostType.GetInterfaces()) { if (type.IsGenericType && type.GetGenericTypeDefinition() == genericListType) { assignGenericListMethod.MakeGenericMethod(type.GetGenericArguments()) .Invoke(this, new object[] { host, i, value }); return; } } // Otherwise just use IList // Expand the list if needed IList list = (IList)host; while (i >= list.Count) { list.Add(null); } list[i] = value; } else if (host is Array) { Array array = (Array)host; int i = TypeCoercer.CoerceToType <int>(this, key); if (i >= array.Length) { throw new ParserException(this, $"Array index out of bounds: {i}, length: {array.Length}"); } array.SetValue(value, i); } else { throw new ParserException(this, $"Unsupported host value type: {hostType}, or unknown property: {key}"); } }
ClassType FillIn(ClassType t, System.Type type) { foreach (System.Type x in type.GetNestedTypes(flags)) { GetType(x); } foreach (FieldInfo x in type.GetFields(BindingFlags.Instance | BindingFlags.Static | flags)) { Field f = t.AddField(new InputElement(x.Name), msg); f.Modifiers = GetFieldModifiers(x); f.Type = GetType(x.FieldType); } foreach (ConstructorInfo x in type.GetConstructors(BindingFlags.Instance | BindingFlags.Static | flags)) { GetMethod(t.AddConstructor(new InputElement(t.Name), msg), x); } foreach (MethodInfo x in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | flags)) { if (x.Name == "get_Item" || x.Name == "set_Item" || type.FullName == "System.String" && x.Name == "get_Chars") { GetMethod(t, x.Name, x); // indexer } else if (x.Name.StartsWith("get_") || x.Name.StartsWith("set_")) { string name = x.Name.Substring(4); Property p = t.members[name] as Property; if (p == null) { p = t.AddProperty(new InputElement(name), msg); } p.Modifiers = GetMethodModifiers(x); Method m; if (x.Name.StartsWith("get_")) { m = p.AddGet(new InputElement(name)); p.Type = GetType(x.ReturnType); } else { m = p.AddSet(new InputElement(name)); m.Type = global.Types.Void; p.Type = GetType(x.GetParameters()[0].ParameterType); } } else { GetMethod(t, x.Name, x); } } t.Modifiers = GetTypeModifiers(type); IList baseinterfaces; if (type.BaseType != null) { t.baseClass = (ClassType)GetType(type.BaseType); baseinterfaces = type.BaseType.GetInterfaces(); } else { baseinterfaces = new System.Type[0]; } if (type.DeclaringType != null) { t.enclosingType = (ClassType)GetType(type.DeclaringType); } foreach (System.Type x in type.GetInterfaces()) { if (!baseinterfaces.Contains(x)) { t.interfaces.Add((InterfaceType)GetType(x)); } } return(t); }
public static IDictionary TestCommonToObject(Stream stream, System.Type configType, System.Type dictType, bool isLoadAll = false, UnityEngine.MonoBehaviour loadAllCortine = null, int maxAsyncReadCnt = 500) { if (stream == null || configType == null || dictType == null) { return(null); } ConfigFileHeader header = new ConfigFileHeader(); if (!header.LoadFromStream(stream) || !header.IsVaild) { return(null); } // 读取索引 stream.Seek(header.indexOffset, SeekOrigin.Begin); // 读取类型(之前已经获取到了) ConfigValueType valueType = (ConfigValueType)stream.ReadByte(); IDictionary maps = null; switch (valueType) { case ConfigValueType.cvObject: { for (uint i = 0; i < header.Count; ++i) { IConfigBase config = Activator.CreateInstance(configType) as IConfigBase; config.stream = stream; System.Object key = config.ReadKEY(); config.dataOffset = FilePathMgr.Instance.ReadLong(stream); if (maps == null) { maps = Activator.CreateInstance(dictType) as IDictionary; } maps[key] = config; } break; } case ConfigValueType.cvList: { var vsType = typeof(List <>).MakeGenericType(configType); for (uint i = 0; i < header.Count; ++i) { IConfigBase config = Activator.CreateInstance(configType) as IConfigBase; config.stream = stream; System.Object key = config.ReadKEY(); long dataOffset = FilePathMgr.Instance.ReadLong(stream); config.dataOffset = dataOffset; int listCnt = FilePathMgr.Instance.ReadInt(stream); if (maps == null) { maps = Activator.CreateInstance(dictType) as IDictionary; } IList list = Activator.CreateInstance(vsType) as IList; maps[key] = list; list.Add(config); for (int j = 1; j < listCnt; ++j) { config = Activator.CreateInstance(configType) as IConfigBase; config.stream = stream; config.dataOffset = dataOffset; list.Add(config); } } break; } // 有问题 case ConfigValueType.cvMap: { Type[] vTypes = dictType.GetInterfaces(); if (vTypes == null || vTypes.Length < 2) { return(null); } Type k1 = vTypes[0]; if (k1 == null) { return(null); } Type vType = vTypes[1]; if (vType == null) { return(null); } if (!vType.IsSubclassOf(typeof(IDictionary))) { return(null); } Type[] subTypes = vType.GetInterfaces(); if (subTypes == null || subTypes.Length < 2) { return(null); } Type k2 = subTypes[0]; Type v = subTypes[1]; if (k2 == null || v == null) { return(null); } var subDictType = typeof(Dictionary <System.Object, System.Object>).MakeGenericType(k2, v); if (subDictType == null) { return(null); } for (uint i = 0; i < header.Count; ++i) { } break; } default: return(null); } if (isLoadAll && maps != null && maps.Count > 0) { StartLoadAllCortine(maps, loadAllCortine, valueType, null, maxAsyncReadCnt); } return(maps); }
/// <summary> /// Run the tests on a given System.Type that is tagged with [TestFixture] /// </summary> /// <param name="fixtureType">The System.Type that will be iterated over for [Test] methods</param> /// <param name="passedTests">Passed tests are appended to this list</param> /// <param name="failedTests">Failed tests are appended to this list</param> /// <param name="longTests">Tests that took longer than mLongExecutionTimeThreshold seconds to complete (pass or fail) are appended to this list</param> /// <returns>Time to run tests in the fixture</returns> private static float RunTestsInFixture(System.Type fixtureType, List <Test> passedTests, List <Test> failedTests, List <Test> longTests) { float runtime = 0.0f; // Scan for [Test] methods in the fixture foreach (MethodInfo testMethodInfo in fixtureType.GetMethods()) { // Each of the attributes on this method foreach (Attribute attrib in Attribute.GetCustomAttributes(testMethodInfo)) { // If this attribute is a Test, run the method if (attrib is Test) { Test test = (Test)attrib; test.ClassName = fixtureType.Name; test.FunctionName = testMethodInfo.Name; System.Object[] args = new System.Object[0]; // Test is run without arguments System.Object fixture = null; try { List <System.Type> interfaces = new List <System.Type>(fixtureType.GetInterfaces()); if (interfaces.Contains(typeof(IDisposable))) { using (IDisposable dFixture = (IDisposable)Activator.CreateInstance(fixtureType)) { test.Start(); testMethodInfo.Invoke(dFixture, args); // If nothing throws; Test Passed } } else { // Instantiate the fixture fixture = Activator.CreateInstance(fixtureType); test.Start(); testMethodInfo.Invoke(fixture, args); // If nothing throws; Test Passed } passedTests.Add(test); } catch (System.Exception e) { test.FailedException = e; failedTests.Add(test); } finally { // Always end the test test.End(); // Kill the fixture fixture = null; // Report if the test took too long to complete if (test.ExecutionTime > mLongExecutionTimeThreshold) { longTests.Add(test); } runtime += test.ExecutionTime; // Force Garbage Collection to reduce side effects // between different test calls. System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } } } } return(runtime); }