當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。