当前位置: 首页>>代码示例>>C#>>正文


C# Type.CreateInstance方法代码示例

本文整理汇总了C#中System.Type.CreateInstance方法的典型用法代码示例。如果您正苦于以下问题:C# Type.CreateInstance方法的具体用法?C# Type.CreateInstance怎么用?C# Type.CreateInstance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Type的用法示例。


在下文中一共展示了Type.CreateInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DeserializeArray

        private static object DeserializeArray(BinaryReader sourceReader, Type elementType, int elementSize, int elementCount)
        {
            var arrayDataAddress = sourceReader.BaseStream.Position;

            var fields = elementType.Fields(
                 Flags.Public |
                 Flags.NonPublic |
                 Flags.Instance);


            List<FieldDelegateInformation> fieldMethods;


            var item = elementType.CreateInstance();
            ProcessFieldTypes(fields, out fieldMethods);


            var array = elementType.MakeArrayType().CreateInstance(elementCount);

            for (var i = 0; i < elementCount; ++i)
            {
                var element = elementType.CreateInstance();
                sourceReader.BaseStream.Position = arrayDataAddress + i * elementSize;
                InvokeFields(sourceReader, element, fields, fieldMethods);
                array.SetElement(i, element);
            }
            return array;
        }
开发者ID:jacksoncougar,项目名称:Moonfish-Editor,代码行数:28,代码来源:Deserializer.cs

示例2: GetModelInterfaceExtenders

 private static ModelInterfaceExtenders GetModelInterfaceExtenders(Type moduleType) {            
     var modelInterfaceExtenders = new ModelInterfaceExtenders();
     if (typeof(XpandModuleBase).IsAssignableFrom(moduleType)){
         XpandModuleBase.CallMonitor.Clear();
         ((XpandModuleBase)moduleType.CreateInstance()).ExtendModelInterfaces(modelInterfaceExtenders);
     }
     if (typeof(IModelExtender).IsAssignableFrom(moduleType))
         ((IModelExtender) moduleType.CreateInstance()).ExtendModelInterfaces(modelInterfaceExtenders);
     return modelInterfaceExtenders;
 }
开发者ID:aries544,项目名称:eXpand,代码行数:10,代码来源:ParsingExtensions.cs

示例3: CreateGroupFromClass

        private static GroupViewModel CreateGroupFromClass(GroupViewModel parent, Type classType, Func<ComfoBoxClient> clientFunc)
        {
            var group = new GroupViewModel(classType.Name);
            parent.Add(group);
            foreach (var subType in classType.GetNestedTypes())
            {
                CreateGroupFromClass(group, subType, clientFunc);
            }

            var instance = classType.CreateInstance();

            foreach (var propertyInfo in classType.Properties(Flags.Default))
            {
                var propertyValue = instance.GetPropertyValue(propertyInfo.Name) as IItemValue;
                if (propertyValue != null && propertyValue.IsReadOnly)
                {
                    group.Add(new ReadOnlyItemViewModel(propertyInfo.Name, clientFunc) {Item = propertyValue});
                }
                else if (propertyValue is AnalogValue || propertyValue is AnalogValue)
                {
                    group.Add(new AnalogValueItemViewModel(propertyInfo.Name, clientFunc) {Item = propertyValue});
                }
                else if (propertyValue is DateValue)
                {
                    group.Add(new ReadOnlyItemViewModel(propertyInfo.Name, clientFunc) {Item = propertyValue});
                }
                else
                {
                    var enumItem = propertyValue as IEnumValue;
                    group.Add(new EnumItemViewModel(propertyInfo.Name, clientFunc) {Item = propertyValue});
                }
            }

            return group;
        }
开发者ID:RF77,项目名称:comfobox-mqtt,代码行数:35,代码来源:GroupFactory.cs

示例4: ExactContractJsonConverterAttribute

		public ExactContractJsonConverterAttribute(Type jsonConverter)
		{
			if (typeof(JsonConverter).IsAssignableFrom(jsonConverter))
			{
				Converter = jsonConverter.CreateInstance<JsonConverter>();
			}
		}
开发者ID:emohebi,项目名称:elasticsearch-net,代码行数:7,代码来源:ContractJsonConverterAttribute.cs

示例5: Convert

            public bool Convert(Type targetType, object owner, ref object value)
            {
                if (!(value is object[]) || !targetType.IsArray)
                    return false;

                if (targetType == typeof(object[]))
                    return true;

                var values = ((object[])value);
                var array = (Array)targetType.CreateInstance(values.Length);
                var elementType = array.GetType().GetElementType();
                for (int i = 0; i < values.Length; i++)
                {
                    object element = values[i];
                    try
                    {
                        if (TryConvert(elementType, owner, ref element))
                            array.SetValue(element, i);
                        else
                            return false;
                    }
                    catch (ImmediateStop)
                    {
                        return false;
                    }
                }
                value = array;
                return true;
            }
开发者ID:buunguyen,项目名称:bike,代码行数:29,代码来源:Interpreter.Interop.Conversion.cs

示例6: HandleException

        public static object HandleException(Exception ex, Type type)
        {
            if (ex is SerializationException
                && ex.Message.Contains("does not have any serializable fields nor properties"))
                return type.CreateInstance();

            throw ex;
        }
开发者ID:CLupica,项目名称:ServiceStack,代码行数:8,代码来源:NetSerializerFormat.cs

示例7: ReturnsResourceAttribute

        public ReturnsResourceAttribute(Type resourceType)
        {
            if (!typeof(ApiResource).GetTypeInfo().IsAssignableFrom(resourceType.GetTypeInfo()))
            {
                throw new ArgumentException("Resource types must implement from Saule.IApiResource");
            }

            Resource = resourceType.CreateInstance<ApiResource>();
        }
开发者ID:robladbrook,项目名称:saule-aspnet5,代码行数:9,代码来源:ReturnsResourceAttribute.cs

示例8: ReturnsResourceAttribute

        /// <summary>
        /// Initializes a new instance of the <see cref="ReturnsResourceAttribute"/> class.
        /// </summary>
        /// <param name="resourceType">The type of the resource this controller action returns.</param>
        public ReturnsResourceAttribute(Type resourceType)
        {
            if (!resourceType.IsSubclassOf(typeof(ApiResource)))
            {
                throw new ArgumentException("Resource types must inherit from Saule.ApiResource");
            }

            Resource = resourceType.CreateInstance<ApiResource>();
        }
开发者ID:markwalsh-liverpool,项目名称:saule,代码行数:13,代码来源:ReturnsResourceAttribute.cs

示例9: CreateDefaultTemplate

 public static ICodeTemplate CreateDefaultTemplate(TemplateType templateType, Session session, Type codeTemplateType, CodeDomProvider codeDomProvider) {
     
     var defaultTemplate = CodeTemplateQuery.FindDefaultTemplate(templateType, session, codeTemplateType,codeDomProvider);
     if (defaultTemplate== null) {
         defaultTemplate = (ICodeTemplate)codeTemplateType.CreateInstance(session);
         defaultTemplate.IsDefault = true;
         defaultTemplate.TemplateType=templateType;
         defaultTemplate.CodeDomProvider=codeDomProvider;
         defaultTemplate.SetDefaults();
     }
     return defaultTemplate;
     
 }
开发者ID:aries544,项目名称:eXpand,代码行数:13,代码来源:CodeTemplateBuilder.cs

示例10: Process

        // <inheritdoc />
        public void Process(Type type)
        {
            if (!(typeof(IComponentManualRegister)).IsAssignableFrom(type))
            {
                return;
            }

            if (!type.IsConcreteType())
            {
                return;
            }

            type.CreateInstance<IComponentManualRegister>().Register(_componentRegistry);
        }
开发者ID:happyframework,项目名称:Happy.Startup,代码行数:15,代码来源:ManualRegisterComponentProcessor.cs

示例11: CreateInstance

		/// <summary>
		///   Creates the target type instance.
		/// </summary>
		/// <param name = "type">The type.</param>
		/// <param name = "configuration">The configuration.</param>
		/// <returns></returns>
		private object CreateInstance(Type type, IConfiguration configuration)
		{
			type = ObtainImplementation(type, configuration);

			var constructor = ChooseConstructor(type);

			object[] args = null;
			if (constructor != null)
			{
				args = ConvertConstructorParameters(constructor, configuration);
			}

			var instance = type.CreateInstance<object>(args);
			return instance;
		}
开发者ID:dohansen,项目名称:Windsor,代码行数:21,代码来源:DefaultComplexConverter.cs

示例12: AddNodeProcessor

		public void AddNodeProcessor(Type type)
		{
			if (type.Is<IXmlNodeProcessor>())
			{
				var processor = type.CreateInstance<IXmlNodeProcessor>();
				foreach(var nodeType in processor.AcceptNodeTypes)
				{
					RegisterProcessor(nodeType, processor);
				}
			}
			else
			{
				throw new XmlProcessorException("{0} does not implement IElementProcessor interface", type.FullName);
			}
		}
开发者ID:Orvid,项目名称:NAntUniversalTasks,代码行数:15,代码来源:DefaultXmlProcessorEngine.cs

示例13: ChangeType

        public static object ChangeType(object value, Type conversionType, CultureInfo cultureInfo) {
            if (value == DBNull.Value)
                value = null;
            if (value == null || value.Equals("")) {
                if (conversionType == typeof(DateTime))
                    return typeof(Nullable).IsAssignableFrom(conversionType) ? (object)null : DateTime.MinValue;
                if (conversionType == typeof(int) || conversionType == typeof(double))
                    return typeof(Nullable).IsAssignableFrom(conversionType) ? (object)null : 0;
                if (conversionType == typeof(bool))
                    return typeof(Nullable).IsAssignableFrom(conversionType) ? (object)null : false;
                if (typeof(IEnumerable).IsAssignableFrom(conversionType) && string.IsNullOrEmpty(value + ""))
                    return null;
                if (conversionType.IsValueType)
                    return conversionType.CreateInstance();
            } else if (typeof(Enum).IsAssignableFrom(conversionType))
                return Enum.Parse(conversionType, (string)value);
            else if ((value + "").IsGuid() && conversionType == typeof(Guid))
                return new Guid(value.ToString());
            else if (value.GetType() == conversionType)
                return value;
            else {
                var o = value as XPBaseObject;
                if (o != null) {
                    if (conversionType == typeof(int))
                        return o.ClassInfo.KeyProperty.GetValue(o);
                    if (conversionType == typeof(string))
                        return o.ClassInfo.KeyProperty.GetValue(o).ToString();
                    return value;
                }
                if (conversionType == typeof(DateTime)) {
                    if ((value + "").Length > 0) {
                        var val = (value + "").Val();
                        if (val > 0)
                            return new DateTime(val);
                    }
                } else if (value.GetType() != conversionType) {
                    if (conversionType.IsNullableType()) {
                        return ChangeType(value, conversionType.GetGenericArguments()[0], cultureInfo);
                    }
                    if (conversionType.IsGenericType) {
                        return value;
                    }
                }
            }

            return Convert.ChangeType(value, conversionType, cultureInfo);

        }
开发者ID:aries544,项目名称:eXpand,代码行数:48,代码来源:XpandReflectionHelper.cs

示例14: Build

        public static object Build(Type requestType, RequestContext requestContext)
        {
            var message = requestType.CreateInstance();
            var properties = requestType.Properties(Flags.InstanceAnyVisibility);
            var queryStringValues = ConvertToRouteValueDictionary(requestContext.HttpContext.Request.QueryString);
            var formValues = ConvertToRouteValueDictionary(requestContext.HttpContext.Request.Form);

            foreach (var property in properties)
            {
                var propertyValue = RetrieveValue(property.Name, property.PropertyType, requestContext, queryStringValues, formValues);

                if (propertyValue == null)
                {
                    continue;
                }

                message.SetPropertyValue(property.Name, propertyValue);
            }

            return message;
        }
开发者ID:mattburton,项目名称:Simple.Web,代码行数:21,代码来源:RequestMessageBuilder.cs

示例15: Deserialize

        public override Object Deserialize(Type t, Json json)
        {
            var m_deserialize = t.GetMethods(BF.All).AssertSingle(m => m.Name == "Deserialize" && (
                Seq.Equal(m.Params(), typeof(Json)) || 
                (Seq.Equal(m.Params(), typeof(Object)) && m.GetParameters()[0].HasAttr<DynamicAttribute>())));
            if (m_deserialize.IsStatic)
            {
                (m_deserialize.Ret() != typeof(void)).AssertTrue();
                return m_deserialize.Invoke(null, json.MkArray());
            }
            else
            {
                var a_json = t.AttrOrNull<JsonAttribute>();
                var default_ctor = a_json == null ? true : a_json.DefaultCtor;
                var instance = default_ctor ? t.CreateInstance() : t.CreateUninitialized();

                (m_deserialize.Ret() == typeof(void)).AssertTrue();
                m_deserialize.Invoke(instance, json.MkArray());
                return instance;
            }
        }
开发者ID:xeno-by,项目名称:xenogears,代码行数:21,代码来源:AdhocEngine.cs


注:本文中的System.Type.CreateInstance方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。