/// <summary> /// <para>Use this to create a new instance of a type using an empty public constructor and Intermediate Language. This used to be faster than Activator.CreateInstance(...),but speaking from own experience this is no longer the case with modern .Net.</para> /// <para>However, the type's constructor is cached when calling CreateInstance, wich makes this faster when creating a lot of the same objects.</para> /// <para>I'm not at all the inventor of this way of working, check for instance this blog post: https://codingsolution.wordpress.com/2013/07/12/activator-createinstance-is-slow/ </para> /// <para>You would use this (or Activator) when you know only a class type, e.g.</para> /// <para>You load a custom text-based save file, if it is a custom type you can cast to an interface in the return type definition:</para> /// <para><![CDATA[ var compilerUnit = new CompilerUnit(); ]]></para> /// <para><![CDATA[ CompilerResults compilerResults = null; ]]></para> /// <para><![CDATA[ Type t = null; ]]></para> /// <para><![CDATA[ Assembly as = compilerUnit.Compile("<Insert code here>", debug, out compilerResults); ]]></para> /// <para><![CDATA[ if (!compilerResults.Errors.HasErrors) { ]]></para> /// <para><![CDATA[ t = _connectionProxyAssembly.GetType("MyNamespace.MyClass"); ]]></para> /// <para><![CDATA[ var obj = FastObjectCreator<IMyInterface>.CreateInstance(t); ]]></para> /// <para><![CDATA[ } ]]></para> /// <para>For primitives and structs Activator is used since they cannot have an explicit parameterless constructor.</para> /// </summary> /// <param name="type"></param> /// <returns></returns> public static T CreateInstance <T>(Type type) { if (type.IsValueType) { return((T)Activator.CreateInstance(type)); } return((T)(GetConstructor(type)())); }
/// <summary> /// 构造对象 /// </summary> public static object Create(Type objectType) { if (objectType == null) { throw new ArgumentNullException(nameof(objectType)); } return(GetConstructor(objectType)()); }
/// <summary> /// Create an instance of the object using the provided meta information. /// </summary> /// <param name="type">A type.</param> /// <param name="metaInfo">The meta information.</param> /// <returns>A fresh instance of the provided type.</returns> public object CreateInstance(Type type, IEnumerable <Tag> metaInfo) { try { return(GetConstructor(type)()); } catch (TargetInvocationException x) { throw new PersistenceException( "Could not instantiate storable object: Encountered exception during constructor call", x.InnerException); } }
public static bool TryParse(string input, Type stronglyTypedIdType, out object result) { if (Guid.TryParse(input, out var id)) { result = GetConstructor(stronglyTypedIdType)(id); return(true); } result = default; return(false); }
public static TTarget CreateInstance <TTarget>() { var instance = default(TTarget); try { instance = (TTarget)GetConstructor <TTarget>()(); } catch (TypeLoadException e) { Debug.WriteLine(e.ToString()); } return(instance); }
public static object CreateInstance(Type pTargetType) { object instance = null; try { instance = GetConstructor(pTargetType)(); } catch (TypeLoadException e) { Debug.WriteLine(e.ToString()); } return(instance); }
T CreateInstance(Type specificType) { // todo: // we can easily merge null-check (in the caller) and GetConstructor() into GetSpecificDeserializerDispatcher() // which would let us avoid one dictionary lookup, the type check, checking if a factory method is set, ... // directly using Expression.New() will likely be faster as well // todo 2: // in fact, we can even *directly* inline the serializer sometimes! // if the specific serializer is a DynamicSerializer, we could just take the expression-tree it generates, and directly inline it here. // that would avoid even more overhead! T value; var factory = _serializer.Config.ObjectFactoryMethod; if (factory != null) { value = (T)_serializer.Config.ObjectFactoryMethod(specificType); } else { value = (T)GetConstructor(specificType)(); } return(value); }
/// <summary> /// 构造对象 /// </summary> public static T Create <T>() where T : class { return((T)GetConstructor(typeof(T))()); }
public void Constructor_AllArguments_SetsProperites() { BadDataFound badDataFound = (context) => { }; IComparer <string> dynamicPropertySort = Comparer <string> .Create((x, y) => x.CompareTo(y)); GetConstructor getConstructor = (type) => type.GetConstructor(null); GetDynamicPropertyName getDynamicPropertyName = (context, field) => string.Empty; HeaderValidated headerValidated = (invalidHeaders, context) => { }; MissingFieldFound missingFieldFound = (headerNames, index, context) => { }; PrepareHeaderForMatch prepareHeaderForMatch = (header, fieldIndex) => header; ReadingExceptionOccurred readingExceptionOccurred = (ex) => true; ReferenceHeaderPrefix referenceHeaderPrefix = (type, memberName) => string.Empty; ShouldQuote shouldQuote = (_, _, _) => true; ShouldSkipRecord shouldSkipRecord = (record) => true; ShouldUseConstructorParameters shouldUseConstructorParameters = (parameterType) => true; var config = new CsvConfiguration(CultureInfo.CurrentCulture, allowComments: true, badDataFound: badDataFound, bufferSize: 1, cacheFields: true, comment: '^', countBytes: true, delimiter: ":", detectColumnCountChanges: true, dynamicPropertySort: dynamicPropertySort, encoding: Encoding.ASCII, escape: '\\', getConstructor: getConstructor, getDynamicPropertyName: getDynamicPropertyName, hasHeaderRecord: false, headerValidated: headerValidated, ignoreBlankLines: false, ignoreReferences: true, includePrivateMembers: true, injectionCharacters: new char[] { '*' }, injectionEscapeCharacter: '`', leaveOpen: true, lineBreakInQuotedFieldIsBadData: true, memberTypes: MemberTypes.Fields, missingFieldFound: missingFieldFound, mode: CsvMode.Escape, newLine: "\n", prepareHeaderForMatch: prepareHeaderForMatch, quote: '\'', readingExceptionOccurred: readingExceptionOccurred, referenceHeaderPrefix: referenceHeaderPrefix, sanitizeForInjection: true, shouldQuote: shouldQuote, shouldSkipRecord: shouldSkipRecord, shouldUseConstructorParameters: shouldUseConstructorParameters, trimOptions: TrimOptions.InsideQuotes, useNewObjectForNullReferenceMembers: false, whiteSpaceChars: new char[] { '~' } ); Assert.IsTrue(config.AllowComments); Assert.AreEqual(badDataFound, config.BadDataFound); Assert.AreEqual(1, config.BufferSize); Assert.IsTrue(config.CacheFields); Assert.AreEqual('^', config.Comment); Assert.IsTrue(config.CountBytes); Assert.AreEqual(CultureInfo.CurrentCulture, config.CultureInfo); Assert.AreEqual(":", config.Delimiter); Assert.IsTrue(config.DetectColumnCountChanges); Assert.AreEqual(dynamicPropertySort, config.DynamicPropertySort); Assert.AreEqual(Encoding.ASCII, config.Encoding); Assert.AreEqual('\\', config.Escape); Assert.AreEqual(getConstructor, config.GetConstructor); Assert.AreEqual(getDynamicPropertyName, config.GetDynamicPropertyName); Assert.IsFalse(config.HasHeaderRecord); Assert.AreEqual(headerValidated, config.HeaderValidated); Assert.IsFalse(config.IgnoreBlankLines); Assert.IsTrue(config.IgnoreReferences); Assert.IsTrue(config.IncludePrivateMembers); Assert.AreEqual('*', config.InjectionCharacters[0]); Assert.AreEqual('`', config.InjectionEscapeCharacter); Assert.IsTrue(config.IsNewLineSet); Assert.IsTrue(config.LeaveOpen); Assert.IsTrue(config.LineBreakInQuotedFieldIsBadData); Assert.AreEqual(MemberTypes.Fields, config.MemberTypes); Assert.AreEqual(missingFieldFound, config.MissingFieldFound); Assert.AreEqual(CsvMode.Escape, config.Mode); Assert.AreEqual("\n", config.NewLine); Assert.AreEqual(prepareHeaderForMatch, config.PrepareHeaderForMatch); Assert.AreEqual('\'', config.Quote); Assert.AreEqual(readingExceptionOccurred, config.ReadingExceptionOccurred); Assert.AreEqual(referenceHeaderPrefix, config.ReferenceHeaderPrefix); Assert.IsTrue(config.SanitizeForInjection); Assert.AreEqual(shouldQuote, config.ShouldQuote); Assert.AreEqual(shouldSkipRecord, config.ShouldSkipRecord); Assert.AreEqual(shouldUseConstructorParameters, config.ShouldUseConstructorParameters); Assert.AreEqual(TrimOptions.InsideQuotes, config.TrimOptions); Assert.IsFalse(config.UseNewObjectForNullReferenceMembers); Assert.AreEqual('~', config.WhiteSpaceChars[0]); }
public static object CreateInstance(Type objType) { return(GetConstructor(objType)()); }
public T GetInstance <T>() { // ReSharper disable once AssignNullToNotNullAttribute return(GetConstructor <T>()()); }
public static object CreateInstance(Type type, ObjectPropertyConvertType convertType, params object[] parameters) { return(GetConstructor(type, convertType)(parameters)); }
public static T InvokeConstructor <T, A, B, C, D>(A a, B b, C c, D d) where T : class { return(GetConstructor <T, A, B, C, D>()(a, b, c, d)); }
public static T InvokeConstructor <T, A, B>(A a, B b) where T : class { return(GetConstructor <T, A, B>()(a, b)); }
public static T InvokeConstructor <T, A>(A a) where T : class { return(GetConstructor <T, A>()(a)); }
public static T InvokeConstructor <T>() where T : class { return(GetConstructor <T>()()); }