GetInterface() private method

private GetInterface ( int index ) : Type
index int
return Type
示例#1
1
        public static object ConvertToFromVector4(ITypeDescriptorContext context, CultureInfo culture, Vector4 value, Type destinationType)
        {
            if (destinationType == typeof(float))
            {
                return value.X;
            }
            if (destinationType == typeof(Vector2))
            {
                return new Vector2(value.X, value.Y);
            }
            if (destinationType == typeof(Vector3))
            {
                return new Vector3(value.X, value.Y, value.Z);
            }
            if (destinationType == typeof(Vector4))
            {
                return new Vector4(value.X, value.Y, value.Z, value.W);
            }
            if (destinationType.GetInterface("IPackedVector") != null)
            {
                IPackedVector packedVec = (IPackedVector) Activator.CreateInstance(destinationType);
                packedVec.PackFromVector4(value);
                return packedVec;
            }

            return null;
        }
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request,MediaTypeHeaderValue mediaType)
        {
            //所需的对象属性
            var includingFields = request.GetRouteData().Values["fields"];
            if (includingFields != null && !string.IsNullOrEmpty(includingFields.ToString()))
            {
                FieldsJsonMediaTypeFormatter frmtr = new FieldsJsonMediaTypeFormatter();
                frmtr.CurrentRequest = request;
                var resolve = new Share.IncludableSerializerContractResolver(this.SerializerSettings.ContractResolver as Share.IgnorableSerializerContractResolver);
                //type.IsAssignableFrom(typeof(IEnumerable<Model.dr_pre_visit>))
                if (type.GetInterface("IEnumerable") != null)
                {
                    resolve.Include(type.GenericTypeArguments[0], includingFields.ToString(), ',');
                }
                else
                {
                    resolve.Include(type, includingFields.ToString(), ",");
                }

                frmtr.SerializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = resolve,
                };
                return frmtr;
            }
            else
            {
                return this;
            }
        }
示例#3
0
        public AggregateDefinition Register(Type aggregateType)
        {
            AggregateDefinition definition = new AggregateDefinition();
            definition.AggregateType = aggregateType;

            var aggregateAttribute = ReflectionUtils.GetSingleAttribute<AggregateAttribute>(aggregateType);
            definition.AggregateName = aggregateAttribute != null 
                ? aggregateAttribute.AggregateName 
                : aggregateType.FullName;

            var statefull = aggregateType.GetInterface(typeof(IStatefullAggregate).FullName);
            if (statefull != null)
            {
                definition.AggregateKind = AggregateKind.Statefull;

                if (aggregateType.BaseType == null
                    || aggregateType.BaseType.IsGenericType == false
                    || aggregateType.BaseType.GetGenericTypeDefinition() != typeof(StatefullAggregate<>))
                    throw new Exception(String.Format("We cannot find state type for [{0}] aggregate", aggregateType.FullName));

                var genericArgs = aggregateType.BaseType.GetGenericArguments();
                definition.StateType = genericArgs[0];
                return definition;
            }

            var stateless = aggregateType.GetInterface(typeof(IStatelessAggregate).FullName);
            if (stateless != null)
            {
                definition.AggregateKind = AggregateKind.Stateless;
                return definition;
            }

            throw new Exception(String.Format("Object of type ({0}) not an aggregate", aggregateType));
        }
		/// <summary>
		/// Overloaded. Returns whether this converter can convert the object to the specified type.
		/// </summary>
		/// <param name="context">An ITypeDescriptorContext that provides a format context.</param>
		/// <param name="destinationType">A Type that represents the type you want to convert to.</param>
		/// <returns>true if this converter can perform the conversion; otherwise, false.</returns>
		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			if (destinationType == null)
				throw new ArgumentNullException("destinationType");

			if( destinationType == typeof(ArrayCollection) )
				return true;
			if( destinationType.IsArray )
				return true;
#if !SILVERLIGHT
			if( destinationType == typeof(ArrayList) )
				return true;
#endif
			if( destinationType == typeof(IList) )
				return true;
			Type typeIList = destinationType.GetInterface("System.Collections.IList", false);
			if(typeIList != null)
				return true;
			//generic interface
			Type typeGenericICollection = destinationType.GetInterface("System.Collections.Generic.ICollection`1", false);
			if (typeGenericICollection != null)
				return true;
#if !SILVERLIGHT
			return base.CanConvertTo(context, destinationType);
#else
            return base.CanConvertTo(destinationType);
#endif
		}
        private static bool IsMemberType(TypeInfo typeInfo)
        {
            if (typeInfo.IsGenericType)
            {
                var implementingType  = GetImplementingType(typeInfo);
                var genericDefinition = implementingType.GetGenericTypeDefinition();

                var arguments = implementingType.GetGenericArguments();
                return(genericDefinition == typeof(RdSignal <>) ||
                       genericDefinition == typeof(RdProperty <>) ||
                       genericDefinition == typeof(RdList <>) ||
                       genericDefinition == typeof(RdSet <>) ||
                       genericDefinition == typeof(RdMap <,>) ||
                       (genericDefinition == typeof(RdCall <,>) && IsScalar(arguments[0]) && IsScalar(arguments[1])) ||
                       // UProperty support
                       typeInfo.GetInterface("JetBrains.Collections.Viewable.IViewableProperty`1")?.GetGenericTypeDefinition() == typeof(IViewableProperty <>) ||
                       // USignal support
                       typeInfo.GetInterface("JetBrains.Collections.Viewable.ISignal`1")?.GetGenericTypeDefinition() == typeof(ISignal <>));
            }

            var hasRdExt = typeInfo.GetCustomAttribute <RdExtAttribute>() != null;

            if (hasRdExt)
            {
                return(true);
            }

            return(false);
        }
        void ExecuteExporter(object x, System.Type type)
        {
            ExportDelegate v;

            if (!Exporters.TryGetValue(type, out v))
            {
                if (type.IsArray)
                {
                    v = ExportArray;
                }
                else if (type.GetInterface("System.Collections.IList") != null)
                {
                    v = ExportIList;
                }
                else if (type.GetInterface("System.Collections.IDictionary") != null)
                {
                    v = ExportIDictionary;
                }
                else if (!type.IsPrimitive)                 // handle user defined types
                {
                    v = CreateUserTypeExporter(x, type);
                }
                else
                {
                    throw new UnsupportedPrimitiveTypeException(type);
                }
                Exporters[type] = v;
            }
            v(this, x);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CollectionDescriptor" /> class.
        /// </summary>
        /// <param name="attributeRegistry">The attribute registry.</param>
        /// <param name="type">The type.</param>
        /// <param name="emitDefaultValues">if set to <c>true</c> [emit default values].</param>
        /// <param name="namingConvention">The naming convention.</param>
        /// <exception cref="System.ArgumentException">Expecting a type inheriting from System.Collections.ICollection;type</exception>
        public CollectionDescriptor(IAttributeRegistry attributeRegistry, Type type, bool emitDefaultValues, IMemberNamingConvention namingConvention)
			: base(attributeRegistry, type, emitDefaultValues, namingConvention)
		{
			if (!IsCollection(type))
				throw new ArgumentException("Expecting a type inheriting from System.Collections.ICollection", "type");

			// Gets the element type
			var collectionType = type.GetInterface(typeof(IEnumerable<>));
			ElementType = (collectionType != null) ? collectionType.GetGenericArguments()[0] : typeof(object);

			// implements ICollection<T> 
			Type itype;
			if ((itype = type.GetInterface(typeof(ICollection<>))) != null)
			{
				var add = itype.GetMethod("Add", new [] { ElementType });
				CollectionAddFunction = (obj, value) => add.Invoke(obj, new [] { value });
				var countMethod = itype.GetProperty("Count").GetGetMethod();
				GetCollectionCountFunction = o => (int)countMethod.Invoke(o, null);
				var isReadOnly = itype.GetProperty("IsReadOnly").GetGetMethod();
				IsReadOnlyFunction = obj => (bool)isReadOnly.Invoke(obj, null);
			    isKeyedCollection = type.ExtendsGeneric(typeof (KeyedCollection<,>));
			}
			// implements IList 
			else if (typeof (IList).IsAssignableFrom(type))
			{
				CollectionAddFunction = (obj, value) => ((IList) obj).Add(value);
				GetCollectionCountFunction = o => ((IList) o).Count;
				IsReadOnlyFunction = obj => ((IList) obj).IsReadOnly;
			}
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="CollectionDescriptor" /> class.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <param name="type">The type.</param>
        /// <exception cref="System.ArgumentException">Expecting a type inheriting from System.Collections.ICollection;type</exception>
        public CollectionDescriptor(ITypeDescriptorFactory factory, Type type) : base(factory, type)
        {
            if (!IsCollection(type))
                throw new ArgumentException("Expecting a type inheriting from System.Collections.ICollection", "type");

            // Gets the element type
            var collectionType = type.GetInterface(typeof(IEnumerable<>));
            ElementType = (collectionType != null) ? collectionType.GetGenericArguments()[0] : typeof(object);
            Category = DescriptorCategory.Collection;
            bool typeSupported = false;

            // implements ICollection<T> 
            Type itype = type.GetInterface(typeof(ICollection<>));
            if (itype != null)
            {
                var add = itype.GetMethod("Add", new[] {ElementType});
                CollectionAddFunction = (obj, value) => add.Invoke(obj, new[] {value});
                var clear = itype.GetMethod("Clear", Type.EmptyTypes);
                CollectionClearFunction = obj => clear.Invoke(obj, EmptyObjects);
                var countMethod = itype.GetProperty("Count").GetGetMethod();
                GetCollectionCountFunction = o => (int)countMethod.Invoke(o, null);
                var isReadOnly = itype.GetProperty("IsReadOnly").GetGetMethod();
                IsReadOnlyFunction = obj => (bool)isReadOnly.Invoke(obj, null);
                typeSupported = true;
            }
            // implements IList<T>
            itype = type.GetInterface(typeof(IList<>));
            if (itype != null)
            {
                var insert = itype.GetMethod("Insert", new[] { typeof(int), ElementType });
                CollectionInsertFunction = (obj, index, value) => insert.Invoke(obj, new[] { index, value });
                var removeAt = itype.GetMethod("RemoveAt", new[] { typeof(int) });
                CollectionRemoveAtFunction = (obj, index) => removeAt.Invoke(obj, new object[] { index });
                var getItem = itype.GetMethod("get_Item", new[] { typeof(int) });
                var setItem = itype.GetMethod("set_Item", new[] { typeof(int), ElementType });
                GetIndexedItem = (obj, index) => getItem.Invoke(obj, new object[] { index });
                SetIndexedItem = (obj, index, value) => setItem.Invoke(obj, new[] { index, value });
                hasIndexerAccessors = true;
            }
            // implements IList
            if (!typeSupported && typeof(IList).IsAssignableFrom(type))
            {
                CollectionAddFunction = (obj, value) => ((IList)obj).Add(value);
                CollectionClearFunction = obj => ((IList)obj).Clear();
                CollectionInsertFunction = (obj, index, value) => ((IList)obj).Insert(index, value);
                CollectionRemoveAtFunction = (obj, index) => ((IList)obj).RemoveAt(index);
                GetCollectionCountFunction = o => ((IList)o).Count;
                GetIndexedItem = (obj, index) => ((IList)obj)[index];
                SetIndexedItem = (obj, index, value) => ((IList)obj)[index] = value;
                IsReadOnlyFunction = obj => ((IList)obj).IsReadOnly;
                hasIndexerAccessors = true;
                typeSupported = true;
            }

            if (!typeSupported)
            {
                throw new ArgumentException("Type [{0}] is not supported as a modifiable collection".ToFormat(type), "type");
            }
        }
 public IBsonSerializer GetSerializer(Type type)
 {
     if (type == typeof(IGameObject) || type.IsSubclassOf(typeof(IGameObject)) || type.GetInterface(typeof(IGameObject).Name) != null)
         return new GameObjectSerializer();
     if (type == typeof(IDataObject) || type.IsSubclassOf(typeof(IDataObject)) || type.GetInterface(typeof(IDataObject).Name) != null)
         return new DataObjectSerializer<IDataObject>();
     return null;
 }
示例#10
0
 public static Vertex Cast(Vertex vertexToCast, Type newVertexType)
 {
     Vertex ret = Activator.CreateInstance(newVertexType) as Vertex;
     ret.Pos = vertexToCast.Pos;
     if (newVertexType.GetInterface("ITextured") != null && vertexToCast is ITextured)
         (ret as ITextured).TexCoord = (vertexToCast as ITextured).TexCoord;
     if (newVertexType.GetInterface("INormal") != null && vertexToCast is INormal)
         (ret as INormal).Normal = (vertexToCast as INormal).Normal;
     if (newVertexType.GetInterface("ITex3") != null && vertexToCast is ITextured)
         (ret as ITex3).TexCoord = (vertexToCast as ITex3).TexCoord;
     return ret;
 }
        IEnumerable<ITypeAmendment> IAmendmentAttribute.GetAmendments(Type target)
        {
            // Class does not implement INotifyPropertyChanged. Implement it for the user.
            if (target.GetCustomAttributes(typeof(NotifyPropertyChangedAttribute), true).Length > 0
                && target.GetInterface("System.ComponentModel.INotifyPropertyChanged") == null)
                yield return (ITypeAmendment)typeof(NotificationAmendment<>).MakeGenericType(target).GetConstructor(Type.EmptyTypes).Invoke(new object[0]);

            // Class implements INotifyPropertyChangedAmendment so that user can fire custom notificaitons
            if (target.GetCustomAttributes(typeof(NotifyPropertyChangedAttribute), true).Length > 0
                && target.GetInterface("NotifyPropertyChanged.INotifyPropertyChangedAmendment") != null)
                yield return (ITypeAmendment)typeof(SimpleNotificationAmendment<>).MakeGenericType(target).GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
        }
 private static void ApplyConverters(Type type, JavaScriptSerializer serializer)
 {
     if (type.GetInterface(typeof(IAsyncUploadConfiguration).FullName) != null)
     {
         serializer.RegisterConverters(new AsyncUploadConfigurationConverter[] { new AsyncUploadConfigurationConverter() });
     }
 }
示例#13
0
 private void GetCommands()
 {
     try
     {
         System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(this.assemblyPath);
         if (assembly != null)
         {
             System.Type[] types = assembly.GetTypes();
             System.Type[] array = types;
             for (int i = 0; i < array.Length; i++)
             {
                 System.Type type = array[i];
                 if (type.GetInterface("ICommand") != null)
                 {
                     ICommand command = assembly.CreateInstance(type.FullName) as ICommand;
                     if (command != null)
                     {
                         this.commandList.Add(command);
                     }
                 }
             }
         }
     }
     catch (System.Exception)
     {
     }
 }
示例#14
0
    /// <summary>
    /// 利用指定的缓存策略提供程序创建 HtmlCacheableAttribute 对象。
    /// </summary>
    /// <param name="policyProviderType">缓存策略提供程序类型</param>
    public CacheableAttribute( Type policyProviderType )
    {
      if ( policyProviderType.GetInterface( mvcCachePolicyProviderType.FullName ) == mvcCachePolicyProviderType )
      {
        CachePolicyProvider = Activator.CreateInstance( policyProviderType ).CastTo<IMvcCachePolicyProvider>();
        return;
      }

      else if ( policyProviderType.GetInterface( cachePolicyProviderType.FullName ) == cachePolicyProviderType )
      {
        CachePolicyProvider = new MvcCachePolicyProviderWrapper( Activator.CreateInstance( policyProviderType ).CastTo<ICachePolicyProvider>() );
        return;
      }

      throw new InvalidOperationException( "配置错误,类型必须从 IHtmlCachePolicyProvider 或 IMvcCachePolicyProvider 派生" );
    }
 // this has been through red and green phase, it has yet to see it's refactor phase
 public Type Close(Type conversionPatternType, Type sourceType, Type targetType)
 {
     var @interface = conversionPatternType.GetInterface(typeof (IConversionPattern<,>));
     if (@interface == null)
     {
         throw new ArgumentException(string.Format("Type {0} doesn't implement {1} and therefore is invalid for this operation.", conversionPatternType, typeof (IConversionPattern<,>)));
     }
     var arguments = @interface.GetGenericArguments();
     var interfaceSourceType = arguments[0];
     var interfaceTargetType = arguments[1];
     if (conversionPatternType.IsGenericType == false)
     {
         if (sourceType.Is(interfaceSourceType) && targetType.Is(interfaceTargetType))
         {
             return conversionPatternType;
         }
         return null;
     }
     var openClassArguments = conversionPatternType.GetGenericArguments();
     var parameters = new Type[openClassArguments.Length];
     if (TryAddParameters(sourceType, interfaceSourceType, parameters, openClassArguments) == false)
     {
         return null;
     }
     if (TryAddParameters(targetType, interfaceTargetType, parameters, openClassArguments) == false)
     {
         return null;
     }
     if (parameters.Any(p => p == null))
     {
         return null;
     }
     return conversionPatternType.MakeGenericType(parameters);
 }
		public AssemblyAnalyzerAttribute (Type Type)
		{
			if (Type.GetInterface (typeof (IAnalyzer).FullName) == null)
				throw new ArgumentException ("AssemblyAnalyzer can only point to types implementing IAnalyzer interface.");

			type = Type;
		}
示例#17
0
        public static Type GetElementType(Type enumerableType)
        {
            if (enumerableType.HasElementType)
            {
                return enumerableType.GetElementType();
            }

            if (enumerableType.IsGenericType && enumerableType.GetGenericTypeDefinition().Equals(typeof (IEnumerable<>)))
            {
                return enumerableType.GetGenericArguments()[0];
            }

            Type ienumerableType = enumerableType.GetInterface("IEnumerable`1");
            if (ienumerableType != null)
            {
                return ienumerableType.GetGenericArguments()[0];
            }

            if (typeof (IEnumerable).IsAssignableFrom(enumerableType))
            {
                return typeof (object);
            }

            throw new ArgumentException(String.Format("Unable to find the element type for type '{0}'.", enumerableType), "enumerableType");
        }
 public override Type GetItemType(Type CollectionType)
 {
     Type t = null;
     if ((t = CollectionType.GetInterface(typeof(ICollection<>).Name)) != null)
     {
         return t.GetGenericArguments()[0];
     }
     else if ((t = CollectionType.GetInterface(typeof(IEnumerable<>).Name)) != null)
     {
         return t.GetGenericArguments()[0];
     }
     else
     {
         return typeof(object);
     }
 }
 /// <summary>
 /// Maps all Models implementing IEntity, and not implementing IFluentIgnore and IMapByCode
 /// </summary>
 /// <param name="type">
 /// The type of model currently being checked
 /// </param>
 /// <returns>
 /// Whether the current type should be automapped or not
 /// </returns>
 public override bool ShouldMap(Type type)
 {
     return
         type.GetInterface(typeof(IEntity).FullName) != null &&
         !type.HasAttribute(typeof(FluentIgnoreAttribute)) &&
         !type.HasAttribute(typeof(MapByCodeAttribute));
 }
示例#20
0
        public IClearMine LoadGame(string path, Type gameType)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(ResourceHelper.FindText("SavedGamePathNotFound"), path);
            }

            if (gameType == null || gameType.GetInterface(typeof(IClearMine).FullName) == null)
            {
                throw new InvalidOperationException(ResourceHelper.FindText("InvalidClearMineGameType", gameType.FullName));
            }

            IClearMine newgame = null;
            var gameLoader = new XmlSerializer(gameType);
            using (var file = File.Open(path, FileMode.Open, FileAccess.Read))
            {
                newgame = gameLoader.Deserialize(file) as IClearMine;
            }

            if (newgame.CheckHash())
            {
                MessageManager.SendMessage<GameLoadMessage>(newgame);
                newgame.ResumeGame();
            }
            else
            {
                MessageBox.Show(ResourceHelper.FindText("CorruptedSavedGameMessage"), ResourceHelper.FindText("CorruptedSavedGameTitle"));
            }

            return newgame;
        }
示例#21
0
        public static object GetGenericRepository(Type genericArgument)
        {
            Type thisType = typeof(GraphRepositoy <T>), currentRepoType = null, interfaceType = null;

            Type[] typelist = GetTypesInNamespace(thisType.Assembly, thisType.Namespace),
            genericArguments = null;

            object genericRepository = null;

            for (int i = 0; i < typelist.Length; i++)
            {
                currentRepoType = typelist[i];
                interfaceType   = currentRepoType.GetInterface("IGraphRepository`1");

                if (interfaceType != null)
                {
                    genericArguments = interfaceType.GetGenericArguments();
                    if (genericArguments != null && genericArguments.Length > 0)
                    {
                        if (genericArgument == genericArguments[0])
                        {
                            genericRepository = Activator.CreateInstance(currentRepoType);
                        }
                    }
                }
            }

            return(genericRepository);
        }
示例#22
0
        public void AddCallback(Type eventType, EventCallback callback)
        {
            if (eventType.GetInterface(typeof(ITradeEvent).Name) == null)
                throw new ArgumentException("Event type should implements " + typeof(ITradeEvent).Name);

            delegates.AddOrUpdate(eventType, callback, (type, eventCallback) => eventCallback + callback);
        }
 public bool CanConvert(Type source, Type target)
 {
     // check if source is convertible
     Type type = source.GetInterface("IConvertible");
     Type type1 = target.GetInterface("IConvertible");
     return type != null && type1 != null;
 }
        public Res<Type, PluginControllerValidationResult> ValidateControllerType(Type controllerType)
        {
            var res = PluginControllerValidationResult.Success;

            if (controllerType == null) throw new ArgumentNullException("Controller type must be supplied");

            try
            {
                res = CChain<PluginControllerValidationResult>
                    // Must be a class
                    .If(() => !controllerType.IsClass, PluginControllerValidationResult.ControllerTypeNotAClass)
                    // Must be marshalable
                    .ThenIf(() => controllerType.BaseType == null || controllerType.BaseType != typeof(CrossAppDomainObject),
                        PluginControllerValidationResult.ControllerTypeNotMarshalable)
                    // Must implement the core controller interface
                    .ThenIf(() => controllerType.GetInterface(typeof(IPluginController).FullName) == null,
                        PluginControllerValidationResult.ControllerInterfaceNotImplemented)
                    // Must have a constructor taking an IKernel
                    //.ThenIf(() => controllerType.GetConstructor(new[] { typeof(IKernel) }) == null,
                    //    PluginControllerValidationResult.KernelAcceptingConstructorNotFound)
                    .Result;

                return new Res<Type, PluginControllerValidationResult>(res == PluginControllerValidationResult.Success,
                    controllerType,
                    res);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Failed to validate controller type", ex);
            }
        }
示例#25
0
 public ValidateAttribute(Type t)
 {
     if (t.BaseType == typeof(IValidator) || t.GetInterface("IValidator") is Type)
         Validator = (IValidator)t.GetConstructor(Type.EmptyTypes).Invoke(null);
     else
         throw new Exception(String.Format("The type {0} doesn't implements IValidator", t.FullName));
 }
示例#26
0
        public void addCommand( string commandName, Type commandClass )
        {
            if ( commandClass == null )
            {
                Debug.LogError ( "Error in " + this + " Command can't be null." );
            }

            if ( commandClass.GetInterface ("IIwCommand") == null )
            {
                Debug.LogError ( "Error in " + this + " Command Class must be extends of IIwCommand interface." );
            }

            lock ( _commandList )
            {
                if ( _commandList.ContainsKey ( commandName ) )
                {
                    _commandList[commandName].Add ( commandClass );
                }
                else
                {
                    List<Type> commandListsByName = new List<Type> ();
                    commandListsByName.Add ( commandClass );
                    _commandList[commandName] = commandListsByName;
                }
            }
        }
示例#27
0
 public bool CanSerialize(Type type) {
   return
     ReflectionTools.HasDefaultConstructor(type) &&
     type.GetInterface(typeof(IEnumerable).FullName) != null &&
     type.GetMethod("Add") != null &&
     type.GetMethod("Add").GetParameters().Length == 1;
 }
示例#28
0
        private static ICodec ActivateCodec(Type assemblyType)
        {
            if (assemblyType.GetInterface(typeof(ICodec).Name) == null)
                return null;

            return Activator.CreateInstance(assemblyType) as ICodec;
        }
示例#29
0
        public static bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(float))
            {
                return true;
            }
            if (destinationType == typeof(Vector2))
            {
                return true;
            }
            if (destinationType == typeof(Vector3))
            {
                return true;
            }
            if (destinationType == typeof(Vector4))
            {
                return true;
            }
            if (destinationType.GetInterface("IPackedVector") != null)
            {
                return true;
            }

            return false;
        }
        private object BindCsv(Type type, string name, ModelBindingContext bindingContext)
        {
            if (type.GetInterface(typeof(IEnumerable).Name) != null)
            {
                var actualValue = bindingContext.ValueProvider.GetValue(name);

                if (actualValue != null)
                {
                    var valueType = type.GetElementType() ?? type.GetGenericArguments().FirstOrDefault();

                    if (valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null)
                    {
                        var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType));

                        foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' }))
                        {
                            if (!String.IsNullOrWhiteSpace(splitValue))
                                list.Add(Convert.ChangeType(splitValue, valueType));
                        }

                        if (type.IsArray)
                            return ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list });
                        else
                            return list;
                    }
                }
            }

            return null;
        }
        public static bool CanBePluggedIntoGenericType(Type pluginType, Type pluggedType, params Type[] templateTypes)
        {
            bool isValid = true;

            Type interfaceType = pluggedType.GetInterface(pluginType.Name);
            if (interfaceType == null)
            {
                interfaceType = pluggedType.BaseType;
            }

            Type[] pluginArgs = pluginType.GetGenericArguments();
            Type[] pluggableArgs = interfaceType.GetGenericArguments();

            if (templateTypes.Length != pluginArgs.Length &&
                pluginArgs.Length != pluggableArgs.Length)
            {
                return false;
            }

            for (int i = 0; i < templateTypes.Length; i++)
            {
                isValid &= templateTypes[i] == pluggableArgs[i] ||
                           pluginArgs[i].IsGenericParameter &&
                           pluggableArgs[i].IsGenericParameter;
            }
            return isValid;
        }
    public ItemsSourceAttribute( Type type )
    {
      var valueSourceInterface = type.GetInterface( typeof( IItemsSource ).FullName );
      if( valueSourceInterface == null )
        throw new ArgumentException( "Type must implement the IItemsSource interface.", "type" );

      Type = type;
    }
示例#33
0
        //IModule instance = null;
        //{if (type == null || type.GetInterface("IModule") == null) continue;
        //instance = (IModule)type.InvokeMember(String.Empty, BindingFlags.CreateInstance, null, null, null);
        //CurrentModules.Add(instance.ModuleId.ToString(), instance);
        //instance.Initializer();}
        #endregion

        private IModule CreateModuleByType(Type type)
        {
            if (type == null || type.GetInterface("IModule") == null) return null;
            var instance = (IModule)type.InvokeMember(String.Empty, BindingFlags.CreateInstance, null, null, null);
            CurrentModules.Add(instance.ModuleId, instance);
            instance.Initializer();
            return instance;
        }
 public void Process(Type type, Registry registry)
 {
     if (!type.Name.Contains("InMemory"))
         return;
     Type interfaceType = type.GetInterface(type.Name.Replace("InMemory", "I"));
     if(interfaceType != null)
         registry.For(interfaceType).LifecycleIs(InstanceScope.Singleton).Use(type);
 }
示例#35
0
        public static IOrmObjectMapping GetObjectDescription(System.Type type)
        {
            if (type.GetInterface(typeof(INHibernateProxy).FullName) != null)
            {
                type = type.BaseType;
            }

            return(OrmMain.ClassMappingList.Find(m => m.ObjectClass == type));
        }
示例#36
0
 private void DisposeImplementation(object instance)
 {
     if (instance != null)
     {
         System.Type type = instance.GetType();
         if (type.GetInterface("System.IDisposable", true) != null)
         {
             type.InvokeMember("Dispose", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, instance, null);
         }
     }
 }
示例#37
0
 public static bool IsGenericDictionary(System.Type clazz)
 {
     if (clazz.IsInterface && clazz.IsGenericType)
     {
         return(typeof(IDictionary <,>).Equals(clazz.GetGenericTypeDefinition()));
     }
     else
     {
         return(clazz.GetInterface(typeof(IDictionary <,>).Name) == null ? false : true);
     }
 }
        private static MethodInfo ValueConvert(System.Type src, System.Type desc)
        {
            var i = desc.GetInterface("IValueBox`1");

            if (i != null)
            {
                var type = i.GetGenericArguments()[0];
                if (AreReferenceAssignable(src, type))
                {
                    return(desc.GetMethod(ParseMethod, PublicStatic));
                }
            }
            return(null);
        }
示例#39
0
        /// <summary>
        /// 获取配置文件中的数据处理类
        /// </summary>
        /// <returns></returns>
        private IDataRecive[] GetDataProcessers()
        {
            List <IDataRecive> _list = new List <IDataRecive>();

            System.Xml.XmlDocument oXml = new System.Xml.XmlDocument();
            oXml.Load(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + "DataProcesser.config");
            System.Xml.XmlNodeList oAssemblyList = oXml.SelectNodes("//assembly");
            for (int k = 0; k < oAssemblyList.Count; k++)
            {
                System.Xml.XmlNodeList     oClassList       = oAssemblyList[k].SelectNodes("//class");
                System.Reflection.Assembly oCurrentAssembly = null;
                try
                {
                    oCurrentAssembly = System.Reflection.Assembly.LoadFile(
                        AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\"
                        + oAssemblyList[k].Attributes["filename"].InnerText);
                }
                catch (System.IO.FileNotFoundException)
                {
                }
                if (oCurrentAssembly == null)
                {
                    continue;
                }
                string strTypeName = null;
                for (int i = 0; i < oClassList.Count; i++)
                {
                    strTypeName = oClassList[i].Attributes["type"].InnerText;
                    System.Type oType = oCurrentAssembly.GetType(strTypeName);
                    if (oType == null)
                    {
                        //throw new NullReferenceException("指定类型不存在:" + strTypeName);
                        continue;
                    }
                    var type = oType.GetInterface(typeof(IDataRecive).Name);
                    if (type != null)
                    {
                        try
                        {
                            var interfaceProcess = (IDataRecive)oCurrentAssembly.CreateInstance(oType.FullName);
                            _list.Add(interfaceProcess);
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return(_list.ToArray());
        }
示例#40
0
        static StackObject *GetInterface_27(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.String @name = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type instance_of_this_method = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetInterface(@name);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
示例#41
0
 /// <summary>
 /// Determines whether or not a given subtype is derived from a basetype or implements the interface basetype.
 /// </summary>
 /// <param name="subtype">The subtype.</param>
 /// <param name="basetype">The basetype.</param>
 /// <returns>If basetype is a class type, the return value is true if subtype derives from basetype. If basetype is an interface, the return value is true if subtype implements the interface basetype. In all other cases the return value is false.</returns>
 public static bool IsSubClassOfOrImplements(System.Type subtype, System.Type basetype)
 {
     if (basetype.IsInterface)
     {
         if (subtype == basetype)
         {
             return(true);
         }
         else
         {
             return(null != subtype.GetInterface(basetype.ToString()));
         }
         //return Array.IndexOf(subtype.GetInterfaces(),basetype)>=0;
     }
     else
     {
         return(subtype.IsSubclassOf(basetype) || subtype == basetype);
     }
 }
示例#42
0
 public void AddType(string sTypeName, System.Type type)
 {
     System.Type tp = type.GetInterface("IEPDataSource");
     if (tp != null)
     {
         int n;
         if (types == null)
         {
             n     = 0;
             types = new DataSourceType[1];
         }
         else
         {
             n = types.Length;
             DataSourceType[] a = new DataSourceType[n + 1];
             for (int i = 0; i < n; i++)
             {
                 if (types[i].type.Equals(type))
                 {
                     n = -1;
                     break;
                 }
                 a[i] = types[i];
             }
             if (n >= 0)
             {
                 types = a;
             }
         }
         if (n >= 0)
         {
             types[n]      = new DataSourceType();
             types[n].Name = sTypeName;
             types[n].type = type;
         }
     }
 }
示例#43
0
 bool _IsValidType(System.Type type)
 {
     if (type == typeof(string))
     {
         return(false);                // because it is not efficient.
     }
     if ((type == typeof(System.WeakReference)) ||
         (type == typeof(DictionaryEntry)))
     {
         return(false);                // Because its value is not always serializable.
     }
     if ((type.FullName == "System.Drawing.Size") ||
         (type.FullName == "System.Drawing.Point") ||
         (type.FullName == "System.Drawing.SizeF"))
     {
         return(false);                        // because it is not efficient.
     }
     if (type.IsADirectGenericOf(typeof(Dictionary <,>)))
     {
         return(false);                // because it is not efficient.
     }
     return((type.GetCustomAttributes(typeof(System.SerializableAttribute), true).Length > 0) ||
            type.GetInterface(typeof(System.Runtime.Serialization.ISerializable).Name) != null);
 }
示例#44
0
        public static Type GetDialogType(System.Type objectClass)
        {
            if (ClassMappingList == null)
            {
                throw new NullReferenceException("ORM Модуль не настроен. Нужно создать ClassMapingList.");
            }

            if (objectClass.GetInterface(typeof(INHibernateProxy).FullName) != null)
            {
                objectClass = objectClass.BaseType;
            }

            IOrmObjectMapping map = ClassMappingList.Find(c => c.ObjectClass == objectClass);

            if (map == null)
            {
                logger.Warn("Диалог для типа {0} не найден.", objectClass);
                return(null);
            }
            else
            {
                return(map.DialogClass);
            }
        }
示例#45
0
    private bool ValidadeDriverClass(string className, out string error)
    {
        error = null;
        if (className == null)
        {
            return(false);
        }
        className = className.Trim();
        if (className.Length == 0)
        {
            return(false);
        }

        System.Type type = null;
        try { type = UOS.Util.GetType(className); }
        catch (System.Exception) { }

        if (type == null)
        {
            error = "invalid class name or type not found";
        }
        else if (type.GetInterface("UOS.UOSDriver") == null)
        {
            error = "does not implement UOSDriver";
        }
        else if ((!type.IsClass) || (type.IsAbstract))
        {
            error = "not a concrete class";
        }
        else if (driverClasses.Contains(driverClass))
        {
            error = "already added this driver";
        }

        return(error == null);
    }
示例#46
0
 public static bool HasInterface(this Type t, Type i)
 {
     return(t != null && i != null && i.IsInterface && t.GetInterface(i.FullName) != null);
 }
示例#47
0
        public void WriteBackingSourceConfig()
        {
            if (!ValidateParameters())
            {
                return;
            }

            System.Reflection.Assembly asm = null;
            Alachisoft.NCache.Config.Dom.Provider[] prov = new Provider[1];

            try
            {
                asm = System.Reflection.Assembly.LoadFrom(AssemblyPath);
            }
            catch (Exception e)
            {
                successFull = false;
                string message = string.Format("Could not load assembly \"" + AssemblyPath + "\". {0}", e.Message);
                OutputProvider.WriteErrorLine("Error: {0}", message);
                return;
            }

            if (asm == null)
            {
                successFull = false;
                throw new Exception("Could not load specified assembly.");
            }

            System.Type type = asm.GetType(Class, true);

            prov[0] = new Provider();
            prov[0].ProviderName     = ProviderName;
            prov[0].AssemblyName     = asm.FullName;
            prov[0].ClassName        = Class;
            prov[0].FullProviderName = asm.GetName().Name + ".dll";
            if (!string.IsNullOrEmpty(Parameters))
            {
                prov[0].Parameters = GetParams(Parameters);
            }
            if (DefaultProvider == true)
            {
                prov[0].IsDefaultProvider = true;
            }
            else
            {
                prov[0].IsDefaultProvider = false;
            }


            if (ReadThru)
            {
                System.Type typeProvider = type.GetInterface("IReadThruProvider");

                if (typeProvider == null)
                {
                    successFull = false;
                    OutputProvider.WriteErrorLine("Error: Specified class does not implement IReadThruProvider.");
                    return;
                }
                else
                {
                    backingSource.Readthru           = new Readthru();
                    backingSource.Readthru.Enabled   = true;
                    backingSource.Readthru.Providers = prov;
                }
            }
            else if (WriteThru)
            {
                System.Type typeProvider = type.GetInterface("IWriteThruProvider");

                if (typeProvider == null)
                {
                    successFull = false;
                    OutputProvider.WriteErrorLine("Error: Specified class does not implement IWriteThruProvider.");
                    return;
                }
                else
                {
                    backingSource.Writethru                          = new Writethru();
                    backingSource.Writethru.Enabled                  = true;
                    backingSource.Writethru.Providers                = prov;
                    backingSource.Writethru.WriteBehind              = new WriteBehind();
                    backingSource.Writethru.WriteBehind.Mode         = "non-batch";
                    backingSource.Writethru.WriteBehind.Throttling   = _operationPerSecond.ToString();
                    backingSource.Writethru.WriteBehind.RequeueLimit = _operationQueueLimit.ToString();
                    backingSource.Writethru.WriteBehind.Eviction     = _operationEvictionRatio.ToString();
                }
            }

            ConfigurationBuilder cfg = new ConfigurationBuilder();
            string output            = cfg.GetSectionXml(backingSource, "backing-source", 1);

            if (string.IsNullOrEmpty(OutputFile))
            {
                OutputProvider.WriteLine(output);
            }
            else
            {
                StringBuilder xml = new StringBuilder();
                xml.Append(output);
                WriteXmlToFile(xml.ToString());
                OutputProvider.WriteLine("BackingSource config for Class " + Class + " is generated at " + OutputFile);
                OutputProvider.WriteLine(System.Environment.NewLine);
            }
        }
示例#48
0
        public bool Validation(T objInstance)
        {
            if (objInstance == null)
            {
                return(false);
            }

            if (this.TargetPropertyInfo == null)
            {
                System.Type targetType = typeof(T);

                object pValue = objInstance;

                if (targetType.GetInterface("System.Collections.ICollection", false) != null)
                {
                    ICollection ienum = (ICollection)pValue;

                    if (ienum == null)
                    {
                        return(false);
                    }
                    else
                    {
                        return((this.MinLength <= ienum.Count) && (this.MaxLength >= ienum.Count));
                    }
                }
                else
                {
                    string str = (string)pValue;

                    if (str == null)
                    {
                        return(false);
                    }

                    return((this.MinLength <= str.Length) && (this.MaxLength >= str.Length));
                }
            }
            else
            {
                System.Type targetType = typeof(T);

                object pValue = this.TargetPropertyInfo.GetValue(objInstance, null);

                if (targetType.GetInterface("System.Collections.ICollection", false) != null)
                {
                    ICollection ienum = (ICollection)pValue;

                    if (ienum == null)
                    {
                        return(false);
                    }
                    else
                    {
                        return((this.MinLength <= ienum.Count) && (this.MaxLength >= ienum.Count));
                    }
                }
                else
                {
                    string str = (string)pValue;

                    if (str == null)
                    {
                        return(false);
                    }

                    return((this.MinLength <= str.Length) && (this.MaxLength >= str.Length));
                }
            }
        }
示例#49
0
 public static bool Handles_Imperative(string name)
 {
     System.Type type = Generator_List[name];
     return(type.GetInterface(
                typeof(GeneratorAda.Imperative_Interface).FullName) != null);
 }