Here are the examples of the csharp api System.Type.GetConstructors() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
629 Examples
19
Source : FluentFeatureRegistrationService.cs
with MIT License
from EmitKnowledge
with MIT License
from EmitKnowledge
private void Register(bool createProxy)
{
var featureType = _featureConfiguration.GetType();
var serviceType = _fluentConfiguration._replacedemblyTypes
.Where(x => x
.GetConstructors()
.Any(ctor => ctor
.GetParameters()
.Any() &&
ctor
.GetParameters()
.All(param => param.ParameterType == featureType)))
.Distinct()
.SingleOrDefault();
var interfaceType = serviceType.GetInterfaces().FirstOrDefault();
object service = Activator.CreateInstance(serviceType, _featureConfiguration);
if (createProxy)
service = FeatureClient.CreateProxy(service, interfaceType, _featureConfiguration);
_fluentConfiguration._registrationCallback(interfaceType, () => service);
}
19
Source : Container.cs
with MIT License
from engthiago
with MIT License
from engthiago
private object ResolveObject(Type contract, IDictionary<Type, Type> dic)
{
// Check for Ciruclar dependencies
CheckForCircularDependencies(contract);
// If this is a concrete type just instantiate it, if not, get the concrete type on the dictionary
Type implementation = contract;
if (implementation.IsAbstract)
{
implementation = dic[contract];
}
this.currentTypes.Add(implementation);
// Get the first available contructor
var constructors = implementation.GetConstructors();
if (constructors.Length < 1)
{
throw new InvalidOperationException($"Onbox Container: {implementation.Name} has no available constructors. The container can not instantiate it.");
}
ConstructorInfo constructor = constructors[0];
ParameterInfo[] constructorParameters = constructor.GetParameters();
if (constructorParameters.Length == 0)
{
if (this.canPrintToConsole)
{
Console.WriteLine("Onbox Container instantiated " + implementation.ToString());
}
currentTypes.Remove(implementation);
return Activator.CreateInstance(implementation);
}
List<object> parameters = new List<object>(constructorParameters.Length);
foreach (ParameterInfo parameterInfo in constructorParameters)
{
var type = parameterInfo.ParameterType;
currentType = implementation;
parameters.Add(this.ResolveObject(type));
}
if (this.canPrintToConsole)
{
Console.WriteLine("Onbox Container instantiated " + implementation.ToString());
}
currentTypes.Remove(implementation);
return constructor.Invoke(parameters.ToArray());
}
19
Source : EntityDataReader.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
static List<Attribute> DiscoverScalarAttributes(Type thisType)
{
//Not a collection of enreplacedies, just an IEnumerable<String> or other scalar type.
//So add just a single Attribute that returns the object itself
if (IsScalarType(thisType))
{
return new List<Attribute> { new Attribute("Value","Value", thisType, t => t,false) };
}
//find all the scalar properties
var allProperties = (from p in thisType.GetProperties()
where IsScalarType(p.PropertyType)
select p).ToList();
//Look for a constructor with arguments that match the properties on name and type
//(name modulo case, which varies between constructor args and properties in coding convention)
//If such an "ordering constructor" exists, return the properties ordered by the corresponding
//constructor args ordinal position.
//An important instance of an ordering constructor, is that C# anonymous types all have one. So
//this enables a simple convention to specify the order of columns projected by the EnreplacedyDataReader
//by simply building the EnreplacedyDataReader from an anonymous type projection.
//If such a constructor is found, replace allProperties with a collection of properties sorted by constructor order.
foreach (var completeConstructor in from ci in thisType.GetConstructors()
where ci.GetParameters().Count() == allProperties.Count()
select ci)
{
var q = (from cp in completeConstructor.GetParameters()
join p in allProperties
on new { n = cp.Name.ToLowerInvariant(), t = cp.ParameterType } equals new { n = p.Name.ToLowerInvariant(), t = p.PropertyType }
select new { cp, p }).ToList();
if (q.Count() == allProperties.Count()) //all constructor parameters matched by name and type to properties
{
//sort all properties by constructor ordinal position
allProperties = ( from o in q
orderby o.cp.Position
select o.p ).ToList();
break; //stop looking for an ordering consturctor
}
}
return allProperties.Select(p => new Attribute(p)).ToList();
}
19
Source : AroundWeaverBase.cs
with MIT License
from erhan0
with MIT License
from erhan0
protected void InitStaticJp()
{
var cons = jpStaticClreplaced.CreateStaticConstructor();
var il = cons.Body.GetILProcessor();
var thisRef = method.DeclaringType.MakeGenerics(JpThisGenericParams);
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Ldftn, invokerMethod.MakeHostInstanceGeneric(thisRef));
il.Append(OpCodes.Newobj, Module.Import(typeof(AdviceInvoker).GetConstructors()[0]));
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Ldftn, callbackMethod.MakeHostGenericSelf());
il.Append(OpCodes.Newobj, Module.Import(typeof(AdviceCallback).GetConstructors()[0]));
il.Append(OpCodes.Ldtoken, method.MakeGenerics(JpMethodGenericParams));
il.Append(OpCodes.Ldtoken, thisRef);
il.Append(OpCodes.Call,
method.Module.ImportMethod<MethodBase>("GetMethodFromHandle", typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle)));
AppendInitializeStaticJp(il);
il.Append(OpCodes.Stsfld, jpStatic.MakeHostGenericSelf());
il.Append(OpCodes.Ret);
}
19
Source : IoCContainer.cs
with MIT License
from evgomes
with MIT License
from evgomes
public object Get(Type type)
{
var constructor = _types[type].GetConstructors()[0];
var constructorParameters = constructor.GetParameters();
if (constructorParameters.Length == 0)
return Activator.CreateInstance(_types[type]);
object[] parameters = new object[constructorParameters.Length];
for (int index = 0; index < constructorParameters.Length; index++)
{
parameters[index] = Get(constructorParameters[index].ParameterType);
}
return constructor.Invoke(parameters);
}
19
Source : Reflector.cs
with MIT License
from fahminlb33
with MIT License
from fahminlb33
public object New(string name, params object[] parameters)
{
var type = GetType(name);
var ctorInfos = type.GetConstructors();
foreach (var ci in ctorInfos)
{
try
{
return ci.Invoke(parameters);
}
catch
{
// ignored
}
}
return null;
}
19
Source : TransientRegistration.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
private NewExpression BuildNewExpression()
{
//检查是否可构造
Helpers.CheckConstructable(typeof(TImplementation));
//获取默认的构造函数
var constructor = typeof(TImplementation).GetConstructors().Single();
var arguments =
from parameter in constructor.GetParameters()
select BuildParameterExpression(parameter.ParameterType);
return Expression.New(constructor, arguments.ToArray());
}
19
Source : ConventionalCatalog.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
private IEnumerable<ImportDefinition> GetImportDefinitions(Type implementationType)
{
var imports = new List<ImportDefinition>();
var defaultConstructor = implementationType.GetConstructors().FirstOrDefault();
if (defaultConstructor != null)
{
foreach (var param in defaultConstructor.GetParameters())
{
imports.Add(
ReflectionModelServices.CreateImportDefinition(
new Lazy<ParameterInfo>(() => param),
AttributedModelServices.GetContractName(param.ParameterType),
AttributedModelServices.GetTypeIdenreplacedy(param.ParameterType),
Enumerable.Empty<KeyValuePair<string, Type>>(),
ImportCardinality.ExactlyOne,
CreationPolicy.Any,
null));
}
}
return imports;
}
19
Source : ReflectionExtension.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
internal static object InternalNew(this Type type, params object[] args)
{
//两个方法存在较大的性能问题,所以需要判断args参数
if (args == null || args.Length == 0)
{
var cons = type.GetConstructor(Type.EmptyTypes);
//查找有默认值参数的构造函数
if (cons == null)
{
cons = type.GetConstructors().FirstOrDefault(s => s.GetParameters().Count(t => t.DefaultValue == DBNull.Value) == 0);
}
if (cons == null)
{
throw new MissingMethodException(SR.GetString(SRKind.NoDefaultOrDefaultValueConstructor));
}
args = new object[cons.GetParameters().Length];
return ReflectionCache.GetInvoker(cons).Invoke(args);
}
return Activator.CreateInstance(type, args);
}
19
Source : Helpers.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
private static bool HreplacedinglePublicConstructor(Type serviceType)
{
return serviceType.GetConstructors().Length == 1;
}
19
Source : Helpers.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
private static ParameterInfo GetFirstInvalidConstructorParameter(Type serviceType)
{
return (
from constructor in serviceType.GetConstructors()
from parameter in constructor.GetParameters()
let type = parameter.ParameterType
where type.IsValueType || type == typeof(string)
select parameter).FirstOrDefault();
}
19
Source : JsonDeserialize.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
private object ParseAnonymousObject(Type type)
{
jsonReader.replacedertAndConsume(JsonTokens.StartObjectLiteralCharacter);
var dic = new Dictionary<string, object>();
var constructor = type.GetConstructors()[0];
var conInvoker = ReflectionCache.GetInvoker(constructor);
var mapper = GenerateParameterDictionary(constructor);
var values = GenerateParameterValues(mapper);
while (true)
{
jsonReader.SkipWhiteSpaces();
var name = jsonReader.ReadKey();
jsonReader.SkipWhiteSpaces();
jsonReader.replacedertAndConsume(JsonTokens.PairSeparator);
jsonReader.SkipWhiteSpaces();
var par = mapper.FirstOrDefault(s => s.Key == name);
if (string.IsNullOrEmpty(par.Key))
{
jsonReader.ReadRaw();
}
else
{
values[name] = Deserialize(par.Value);
}
jsonReader.SkipWhiteSpaces();
if (jsonReader.replacedertNextIsDelimiterOrSeparator(JsonTokens.EndObjectLiteralCharacter))
{
break;
}
}
return conInvoker.Invoke(values.Values.ToArray());
}
19
Source : AnonymousRowMapper.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
protected virtual Expression<Func<IDataReader, T>> BuildExpressionForDataReader()
{
var conInfo = typeof(T).GetConstructors().FirstOrDefault();
Guard.NullReference(conInfo);
var parExp = Expression.Parameter(typeof(IDataReader), "s");
var convertMethod = typeof(GenericExtension).GetMethod("ToType");
var itemGetMethod = typeof(IRecordWrapper).GetMethod("GetValue", new[] { typeof(IDataReader), typeof(string) });
var parameters =
GetParameters(conInfo).Select(s => (Expression)Expression.Convert(
Expression.Call(convertMethod, new Expression[]
{
Expression.Call(Expression.Constant(RecordWrapper), itemGetMethod, new Expression[] { parExp, Expression.Constant(s.Name) }),
Expression.Constant(s.ParameterType),
Expression.Constant(null)
}
), s.ParameterType));
var newExp = Expression.New(conInfo, parameters);
return Expression.Lambda<Func<IDataReader, T>>(
Expression.MemberInit(newExp), parExp);
}
19
Source : AnonymousRowMapper.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
protected virtual Expression<Func<DataRow, T>> BuildExpressionForDataRow()
{
var conInfo = typeof(T).GetConstructors().FirstOrDefault();
Guard.NullReference(conInfo);
var parExp = Expression.Parameter(typeof(DataRow), "s");
var convertMethod = typeof(GenericExtension).GetMethod("ToType");
#if N35
var itemGetMethod = typeof(DataRow).GetMethod("get_Item", new[] { typeof(string) });
#else
var itemProperty = typeof(DataRow).GetProperty("Item", new[] { typeof(string) });
#endif
var parameters =
GetParameters(conInfo).Select(s => (Expression)Expression.Convert(
Expression.Call(convertMethod, new Expression[]
{
#if N35
Expression.Call(parExp, itemGetMethod, Expression.Constant(s.Name)),
#else
Expression.MakeIndex(parExp, itemProperty, new List<Expression> { Expression.Constant(s.Name) }),
#endif
Expression.Constant(s.ParameterType),
Expression.Constant(null)
}
), s.ParameterType));
var newExp = Expression.New(conInfo, parameters);
return Expression.Lambda<Func<DataRow, T>>(
Expression.MemberInit(newExp), parExp);
}
19
Source : ExecutionBuilder.cs
with GNU General Public License v3.0
from faib920
with GNU General Public License v3.0
from faib920
private Expression CreateParameterCollectionExpression(Expression expression)
{
var namedValues = NamedValueGatherer.Gather(expression);
var values = namedValues.Select(v => Expression.Convert(this.Visit(v.Value), typeof(object))).ToArray();
if (values.Length > 0)
{
var arguments = new List<Expression>();
var constructor = typeof(Parameter).GetConstructor(new[] { typeof(string), typeof(object) });
for (var i = 0; i < namedValues.Count; i++)
{
Expression pv = values[i] is Expression ?
(Expression)values[i] :
Expression.Constant(values[i], typeof(object));
var pExp = Expression.New(constructor, Expression.Constant(namedValues[i].Name), pv);
arguments.Add(pExp);
}
var listExp = Expression.ListInit(Expression.New(typeof(List<Parameter>)), arguments);
return Expression.New(typeof(ParameterCollection).GetConstructors()[1], listExp);
}
else
{
return Expression.Constant(null, typeof(ParameterCollection));
}
}
19
Source : TransientRegistration.cs
with GNU Lesser General Public License v3.0
from faib920
with GNU Lesser General Public License v3.0
from faib920
private NewExpression BuildNewExpression()
{
ConstructorInfo[] constructors = null;
if (typeof(IAopSupport).IsreplacedignableFrom(typeof(TImplementation)))
{
constructors = AspectFactory.GetProxyType(typeof(TImplementation)).GetConstructors();
}
else
{
constructors = typeof(TImplementation).GetConstructors();
}
if (constructors.Length != 1)
{
throw new InvalidOperationException(SR.GetString(SRKind.NoDefaultConstructor, typeof(TImplementation)));
}
var constructor = constructors[0];
foreach (var par in constructor.GetParameters())
{
if (!_container.IsRegistered(par.ParameterType))
{
throw new InvalidOperationException(SR.GetString(SRKind.NotFoundRegisterForType, par.ParameterType));
}
}
var arguments =
from parameter in constructor.GetParameters()
select BuildParameterExpression(parameter.ParameterType);
return Expression.New(constructor, arguments.ToArray());
}
19
Source : ReflectionExtension.cs
with GNU Lesser General Public License v3.0
from faib920
with GNU Lesser General Public License v3.0
from faib920
internal static object InternalNew(this Type type, params object[] args)
{
if (args == null || args.Length == 0)
{
return Activator.CreateInstance(type);
}
else
{
var constructors = type.GetConstructors();
var cons = constructors.Length == 1 ? constructors[0] :
constructors.FirstOrDefault(c => IsMatchConstructor(c, args));
if (cons == null)
{
throw new MissingMethodException(SR.GetString(SRKind.NoMatchConstructor));
}
return ReflectionCache.GetInvoker(cons).Invoke(args);
}
}
19
Source : JsonDeserialize.cs
with GNU Lesser General Public License v3.0
from faib920
with GNU Lesser General Public License v3.0
from faib920
private object ParseAnonymousObject(Type type)
{
_jsonReader.replacedertAndConsume(JsonTokens.StartObjectLiteralCharacter);
var dic = new Dictionary<string, object>();
var constructor = type.GetConstructors()[0];
var conInvoker = ReflectionCache.GetInvoker(constructor);
var mapper = GenerateParameterDictionary(constructor);
var values = GenerateParameterValues(mapper);
while (true)
{
_jsonReader.SkipWhiteSpaces();
var name = _jsonReader.ReadKey();
_jsonReader.SkipWhiteSpaces();
_jsonReader.replacedertAndConsume(JsonTokens.PairSeparator);
_jsonReader.SkipWhiteSpaces();
var par = mapper.FirstOrDefault(s => s.Key == name);
if (string.IsNullOrEmpty(par.Key))
{
_jsonReader.ReadRaw();
}
else
{
values[name] = Deserialize(par.Value);
}
_jsonReader.SkipWhiteSpaces();
if (_jsonReader.replacedertNextIsDelimiterOrSeparator(JsonTokens.EndObjectLiteralCharacter))
{
break;
}
}
return conInvoker.Invoke(values.Values.ToArray());
}
19
Source : AnonymousRowMapper.cs
with GNU Lesser General Public License v3.0
from faib920
with GNU Lesser General Public License v3.0
from faib920
protected virtual Expression<Func<IDataReader, T>> BuildExpressionForDataReader()
{
var conInfo = typeof(T).GetConstructors().FirstOrDefault();
Guard.NullReference(conInfo);
var parExp = Expression.Parameter(typeof(IDataReader), "s");
var parameters =
GetParameters(conInfo).Select(s => (Expression)Expression.Convert(
Expression.Call(MethodCache.ToType, new Expression[]
{
Expression.Call(Expression.Constant(RecordWrapper), MethodCache.GetValue, new Expression[] { parExp, Expression.Constant(s.Name) }),
Expression.Constant(s.ParameterType),
Expression.Constant(null)
}
), s.ParameterType));
var newExp = Expression.New(conInfo, parameters);
return Expression.Lambda<Func<IDataReader, T>>(
Expression.MemberInit(newExp), parExp);
}
19
Source : QueryProviderCache.cs
with GNU Lesser General Public License v3.0
from faib920
with GNU Lesser General Public License v3.0
from faib920
internal static IQueryable Create(Type type, IQueryProvider queryProvider, Expression expression)
{
var func = _cache.GetOrAdd(type, key =>
{
var rcons = typeof(QuerySet<>).MakeGenericType(key).GetConstructors()[1];
var parExp1 = Expression.Parameter(typeof(IQueryProvider));
var parExp2 = Expression.Parameter(typeof(Expression));
var newExp = Expression.New(rcons, parExp1, parExp2);
var lambdaExp = Expression.Lambda<Func<IQueryProvider, Expression, IQueryable>>(newExp, parExp1, parExp2);
return lambdaExp.Compile();
});
return func(queryProvider, expression);
}
19
Source : HandlerCreator.cs
with GNU Lesser General Public License v3.0
from faib920
with GNU Lesser General Public License v3.0
from faib920
internal static WebSocketHandler CreateHandler(IServiceProvider serviceProvider, WebSocketBuildOption option, Type handlerType)
{
if (handlerType == null || !typeof(WebSocketHandler).IsreplacedignableFrom(handlerType))
{
return null;
}
var constructor = handlerType.GetConstructors().FirstOrDefault();
if (constructor == null)
{
throw new Exception($"No default constructor of {handlerType}.");
}
var parameters = constructor.GetParameters();
var arguments = new object[parameters.Length];
if (serviceProvider != null)
{
for (var i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType == typeof(IServiceProvider))
{
arguments[i] = serviceProvider;
}
else if (parameters[i].ParameterType == typeof(WebSocketBuildOption))
{
arguments[i] = option;
}
else
{
arguments[i] = serviceProvider.GetService(parameters[i].ParameterType);
}
}
}
return (WebSocketHandler)constructor.Invoke(arguments);
}
19
Source : ServiceProxyFactory.cs
with MIT License
from fanliang11
with MIT License
from fanliang11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public object CreateProxy(Type type)
{
var instance = ServiceResolver.Current.GetService(type);
if (instance == null)
{
var proxyType = _serviceTypes.Single(type.GetTypeInfo().IsreplacedignableFrom);
instance = proxyType.GetTypeInfo().GetConstructors().First().Invoke(new object[] { _remoteInvokeService, _typeConvertibleService, null,
_serviceProvider.GetService<CPlatformContainer>(),_serviceRouteProvider});
ServiceResolver.Current.Register(null, instance, type);
}
return instance;
}
19
Source : ServiceProxyFactory.cs
with MIT License
from fanliang11
with MIT License
from fanliang11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public object CreateProxy(string key,Type type)
{
var instance = ServiceResolver.Current.GetService(type,key);
if (instance == null)
{
var proxyType = _serviceTypes.Single(type.GetTypeInfo().IsreplacedignableFrom);
instance = proxyType.GetTypeInfo().GetConstructors().First().Invoke(new object[] { _remoteInvokeService, _typeConvertibleService, key,
_serviceProvider.GetService<CPlatformContainer>(),_serviceRouteProvider});
ServiceResolver.Current.Register(key, instance, type);
}
return instance;
}
19
Source : ServiceProxyFactory.cs
with MIT License
from fanliang11
with MIT License
from fanliang11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T CreateProxy<T>(string key) where T:clreplaced
{
var instanceType = typeof(T);
var instance = ServiceResolver.Current.GetService(instanceType, key);
if (instance == null)
{
var proxyType = _serviceTypes.Single(typeof(T).GetTypeInfo().IsreplacedignableFrom);
instance = proxyType.GetTypeInfo().GetConstructors().First().Invoke(new object[] { _remoteInvokeService, _typeConvertibleService,key,
_serviceProvider.GetService<CPlatformContainer>(),_serviceRouteProvider });
ServiceResolver.Current.Register(key, instance, instanceType);
}
return instance as T;
}
19
Source : Readers.cs
with Apache License 2.0
from FieldWarning
with Apache License 2.0
from FieldWarning
internal static void InitializeReaders(ILProcessor worker)
{
ModuleDefinition module = Weaver.Currentreplacedembly.MainModule;
TypeReference genericReaderClreplacedRef = module.ImportReference(typeof(Reader<>));
System.Reflection.FieldInfo fieldInfo = typeof(Reader<>).GetField(nameof(Reader<object>.read));
FieldReference fieldRef = module.ImportReference(fieldInfo);
TypeReference networkReaderRef = module.ImportReference(typeof(NetworkReader));
TypeReference funcRef = module.ImportReference(typeof(Func<,>));
MethodReference funcConstructorRef = module.ImportReference(typeof(Func<,>).GetConstructors()[0]);
foreach (KeyValuePair<TypeReference, MethodReference> kvp in readFuncs)
{
TypeReference targetType = kvp.Key;
MethodReference readFunc = kvp.Value;
// create a Func<NetworkReader, T> delegate
worker.Append(worker.Create(OpCodes.Ldnull));
worker.Append(worker.Create(OpCodes.Ldftn, readFunc));
GenericInstanceType funcGenericInstance = funcRef.MakeGenericInstanceType(networkReaderRef, targetType);
MethodReference funcConstructorInstance = funcConstructorRef.MakeHostInstanceGeneric(funcGenericInstance);
worker.Append(worker.Create(OpCodes.Newobj, funcConstructorInstance));
// save it in Reader<T>.read
GenericInstanceType genericInstance = genericReaderClreplacedRef.MakeGenericInstanceType(targetType);
FieldReference specializedField = fieldRef.SpecializeField(genericInstance);
worker.Append(worker.Create(OpCodes.Stsfld, specializedField));
}
}
19
Source : Writers.cs
with Apache License 2.0
from FieldWarning
with Apache License 2.0
from FieldWarning
internal static void InitializeWriters(ILProcessor worker)
{
ModuleDefinition module = Weaver.Currentreplacedembly.MainModule;
TypeReference genericWriterClreplacedRef = module.ImportReference(typeof(Writer<>));
System.Reflection.FieldInfo fieldInfo = typeof(Writer<>).GetField(nameof(Writer<object>.write));
FieldReference fieldRef = module.ImportReference(fieldInfo);
TypeReference networkWriterRef = module.ImportReference(typeof(NetworkWriter));
TypeReference actionRef = module.ImportReference(typeof(Action<,>));
MethodReference actionConstructorRef = module.ImportReference(typeof(Action<,>).GetConstructors()[0]);
foreach (KeyValuePair<TypeReference, MethodReference> kvp in writeFuncs)
{
TypeReference targetType = kvp.Key;
MethodReference writeFunc = kvp.Value;
// create a Action<NetworkWriter, T> delegate
worker.Append(worker.Create(OpCodes.Ldnull));
worker.Append(worker.Create(OpCodes.Ldftn, writeFunc));
GenericInstanceType actionGenericInstance = actionRef.MakeGenericInstanceType(networkWriterRef, targetType);
MethodReference actionRefInstance = actionConstructorRef.MakeHostInstanceGeneric(actionGenericInstance);
worker.Append(worker.Create(OpCodes.Newobj, actionRefInstance));
// save it in Writer<T>.write
GenericInstanceType genericInstance = genericWriterClreplacedRef.MakeGenericInstanceType(targetType);
FieldReference specializedField = fieldRef.SpecializeField(genericInstance);
worker.Append(worker.Create(OpCodes.Stsfld, specializedField));
}
}
19
Source : Readers.cs
with Mozilla Public License 2.0
from finol-digital
with Mozilla Public License 2.0
from finol-digital
internal static void InitializeReaders(ILProcessor worker)
{
ModuleDefinition module = Weaver.Currentreplacedembly.MainModule;
TypeReference genericReaderClreplacedRef = module.ImportReference(typeof(Reader<>));
System.Reflection.FieldInfo fieldInfo = typeof(Reader<>).GetField(nameof(Reader<object>.read));
FieldReference fieldRef = module.ImportReference(fieldInfo);
TypeReference networkReaderRef = module.ImportReference(typeof(NetworkReader));
TypeReference funcRef = module.ImportReference(typeof(Func<,>));
MethodReference funcConstructorRef = module.ImportReference(typeof(Func<,>).GetConstructors()[0]);
foreach (KeyValuePair<TypeReference, MethodReference> kvp in readFuncs)
{
TypeReference targetType = kvp.Key;
MethodReference readFunc = kvp.Value;
// create a Func<NetworkReader, T> delegate
worker.Emit(OpCodes.Ldnull);
worker.Emit(OpCodes.Ldftn, readFunc);
GenericInstanceType funcGenericInstance = funcRef.MakeGenericInstanceType(networkReaderRef, targetType);
MethodReference funcConstructorInstance = funcConstructorRef.MakeHostInstanceGeneric(funcGenericInstance);
worker.Emit(OpCodes.Newobj, funcConstructorInstance);
// save it in Reader<T>.read
GenericInstanceType genericInstance = genericReaderClreplacedRef.MakeGenericInstanceType(targetType);
FieldReference specializedField = fieldRef.SpecializeField(genericInstance);
worker.Emit(OpCodes.Stsfld, specializedField);
}
}
19
Source : Writers.cs
with Mozilla Public License 2.0
from finol-digital
with Mozilla Public License 2.0
from finol-digital
internal static void InitializeWriters(ILProcessor worker)
{
ModuleDefinition module = Weaver.Currentreplacedembly.MainModule;
TypeReference genericWriterClreplacedRef = module.ImportReference(typeof(Writer<>));
System.Reflection.FieldInfo fieldInfo = typeof(Writer<>).GetField(nameof(Writer<object>.write));
FieldReference fieldRef = module.ImportReference(fieldInfo);
TypeReference networkWriterRef = module.ImportReference(typeof(NetworkWriter));
TypeReference actionRef = module.ImportReference(typeof(Action<,>));
MethodReference actionConstructorRef = module.ImportReference(typeof(Action<,>).GetConstructors()[0]);
foreach (KeyValuePair<TypeReference, MethodReference> kvp in writeFuncs)
{
TypeReference targetType = kvp.Key;
MethodReference writeFunc = kvp.Value;
// create a Action<NetworkWriter, T> delegate
worker.Emit(OpCodes.Ldnull);
worker.Emit(OpCodes.Ldftn, writeFunc);
GenericInstanceType actionGenericInstance = actionRef.MakeGenericInstanceType(networkWriterRef, targetType);
MethodReference actionRefInstance = actionConstructorRef.MakeHostInstanceGeneric(actionGenericInstance);
worker.Emit(OpCodes.Newobj, actionRefInstance);
// save it in Writer<T>.write
GenericInstanceType genericInstance = genericWriterClreplacedRef.MakeGenericInstanceType(targetType);
FieldReference specializedField = fieldRef.SpecializeField(genericInstance);
worker.Emit(OpCodes.Stsfld, specializedField);
}
}
19
Source : DependencyInjectionJobExecutor.cs
with MIT License
from FrodaSE
with MIT License
from FrodaSE
public Task<JobResult> ExecuteAsync(JobDescription jobDescription, IDependencyResolver resolver = null)
{
var type = Type.GetType(jobDescription.Type);
var typeInfo = type.GetTypeInfo();
ConstructorInfo ctor = typeInfo.GetConstructors().Single();
ParameterInfo[] parameters = ctor.GetParameters();
if (parameters.Length > 0 && resolver == null)
{
throw new InvalidOperationException("Cannot resolve dependencies without a dependency resolver.");
}
var arguments = parameters
.Select(p => resolver.Resolve(p.ParameterType, out var resolvedType)
? resolvedType
: throw new InvalidOperationException(
$"Could not resolve parameter of type: {p.ParameterType.replacedemblyQualifiedName}"))
.ToArray();
object jobInstance = ctor.Invoke(arguments);
switch (jobInstance)
{
case Job job:
return job.ExecuteAsync();
case JobInputBase inputJob:
return inputJob.DoExecuteAsync(jobDescription.Input.InputData);
default:
throw new ArgumentOutOfRangeException(nameof(jobInstance), "Unknown job type.");
}
}
19
Source : AopInitializer.cs
with MIT License
from fs7744
with MIT License
from fs7744
public static Func<IServiceProvider, object> CreateFacadeInstanceCreator(this Type type)
{
var constructor = type.GetConstructors().FirstOrDefault(i => i.IsPublic && i.IsDefined(typeof(DynamicProxyAttribute), false));
if (constructor == null) return null;
var method = new DynamicMethod(Guid.NewGuid().ToString("N"), typeof(object), Constants.DefaultConstructorParameters);
var il = method.GetILGenerator();
il.EmitLoadArg(0);
il.Emit(OpCodes.Newobj, constructor);
il.Emit(OpCodes.Ret);
return (Func<IServiceProvider, object>)method.CreateDelegate(typeof(Func<IServiceProvider, object>));
}
19
Source : DotNetReflection.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public object Instantiate(string typeName, params object[] args)
{
var type = _typeMap.ResolveType(typeName);
if (type == null)
throw new TypeNotFound(typeName);
return TryInvokeExtension.Try(
() => (type.IsValueType && args.Length == 0)
? FormatterServices.GetUninitializedObject(type)
: type.GetConstructors().First(c => c.GetParameters().ParametersMatch(args)).Invoke(args));
}
19
Source : Generator.cs
with Apache License 2.0
from fy0
with Apache License 2.0
from fy0
static TypingGenInfo ToTypingGenInfo(IEnumerable<Type> types)
{
HashSet<Type> genTypeSet = new HashSet<Type>();
HashSet<Type> workTypes = new HashSet<Type>();
HashSet<Type> refTypes = new HashSet<Type>();
foreach (var type in types)
{
AddRefType(workTypes, refTypes, type);
var defType = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
if (!genTypeSet.Contains(defType)) genTypeSet.Add(defType);
foreach (var field in type.GetFields(Flags))
{
AddRefType(workTypes, refTypes, field.FieldType);
}
foreach(var method in type.GetMethods(Flags))
{
AddRefType(workTypes, refTypes, method.ReturnType);
foreach(var pinfo in method.GetParameters())
{
AddRefType(workTypes, refTypes, pinfo.ParameterType);
}
}
foreach(var constructor in type.GetConstructors())
{
foreach (var pinfo in constructor.GetParameters())
{
AddRefType(workTypes, refTypes, pinfo.ParameterType);
}
}
}
if (!genTypeSet.Contains(typeof(Array)) && !refTypes.Contains(typeof(Array))) AddRefType(workTypes, refTypes, typeof(Array));
var tsTypeGenInfos = new Dictionary<string, TsTypeGenInfo>();
foreach (var t in refTypes.Distinct())
{
var info = ToTsTypeGenInfo(t, genTypeSet);
var name = (string.IsNullOrEmpty(info.Namespace) ? "" : (info.Namespace + ".")) + info.Name;
if (info.IsGenericTypeDefinition)
name += "<" + string.Join(",", info.GenericParameters) + ">";
tsTypeGenInfos.Add(name, info);
}
foreach (var info in tsTypeGenInfos)
{
CheckMethodGenInfos(tsTypeGenInfos, info.Value);
}
return new TypingGenInfo()
{
NamespaceInfos = tsTypeGenInfos.Values.GroupBy(t => t.Namespace)
.Select(g => new TsNamespaceGenInfo()
{
Name = g.Key,
Types = g.ToArray()
}).ToArray(),
#if CSHARP_7_3_OR_NEWER
TaskDef = refTypes.Contains(typeof(System.Threading.Tasks.Task<>)) ?
"type $Task<T> = System.Threading.Tasks.Task$1<T>"
: "interface $Task<T> {}",
#else
TaskDef = "interface $Task<T> {}",
#endif
};
}
19
Source : GrainsWarmup.cs
with Apache License 2.0
from gigya
with Apache License 2.0
from gigya
public void Warmup()
{
// We cannot use Orleans to obtain grains (to warm them up); Orleans only provides lazy grain references, and we'd
// have to call a method on the grain to activate it, but there's no generic method we could call. So we instantiate
// grains through Ninject instead of Orleans to register their dependencies in Ninject. When Orleans will instantiate
// these grains, their non-transient dependencies will already be registered in Ninject, saving startup time.
try
{
List<string> failedWarmupWarn = new List<string>();
foreach (Type serviceClreplaced in _orleansMapper.ServiceClreplacedesTypes)
{
try
{
foreach (Type parameterType in serviceClreplaced.GetConstructors()
.SelectMany(ctor => ctor.GetParameters().Select(p => p.ParameterType)).Distinct())
{
try
{
if (!_kernel.CanResolve(parameterType))
{
if (_orleansInternalTypes.Contains(parameterType) || _orleansInternalTypesString.Any(x => parameterType.FullName.Contains(x)))
{
//No waring on Orleans type
continue;
}
failedWarmupWarn.Add($"Type {parameterType} of grain {serviceClreplaced}");
continue;
}
// Try to warm up dependency
_kernel.Get(parameterType);
}
catch//No exception handling needed. We try to warmup all constructor types. In case of failure, write the warning for non orleans types and go to the next type
{
failedWarmupWarn.Add($"Type {parameterType} of grain {serviceClreplaced}");
}
}
}
catch (Exception e)
{
_log.Warn($"Failed to warmup grain {serviceClreplaced}", e);
}
}
if (failedWarmupWarn.Count > 0)
{
_log.Warn($"Fail to warmup the following types:\n{string.Join("\n", failedWarmupWarn)}");
}
}
catch (Exception ex)
{
_log.Warn("Failed to warmup grains", ex);
}
}
19
Source : GraphSchemaBuilder.cs
with MIT License
from graphql-aspnet
with MIT License
from graphql-aspnet
public static TSchema BuildSchema<TSchema>(IServiceProvider sp)
where TSchema : clreplaced, ISchema
{
Validation.ThrowIfNull(sp, nameof(sp));
List<object> paramSet = null;
if (!SCHEMA_CONSTRUCTORS.TryGetValue(typeof(TSchema), out var schemaConstructor))
{
// attempt to find a constructor for which all all its parameters are present on the DI container
// then build the schema
var constructors = typeof(TSchema).GetConstructors().OrderByDescending(x => x.GetParameters().Length);
foreach (var constructor in constructors)
{
paramSet = RetrieveConstructorParams(sp, constructor);
if (paramSet != null)
{
schemaConstructor = constructor;
break;
}
}
SCHEMA_CONSTRUCTORS.TryAdd(typeof(TSchema), schemaConstructor);
}
if (schemaConstructor != null && paramSet == null)
paramSet = RetrieveConstructorParams(sp, schemaConstructor);
if (paramSet == null)
{
throw new InvalidOperationException("No suitable constructors found " +
$"to properly instantiate schema '{typeof(TSchema).FriendlyName()}'.");
}
return InstanceFactory.CreateInstance(typeof(TSchema), paramSet.ToArray()) as TSchema;
}
19
Source : SimpleContainer.cs
with MIT License
from graphql-dotnet
with MIT License
from graphql-dotnet
private object CreateInstance(Type implementationType)
{
var ctor = implementationType.GetConstructors().OrderByDescending(x => x.GetParameters().Length).First();
var parameterTypes = ctor.GetParameters().Select(p => p.ParameterType);
var dependencies = parameterTypes.Select(Get).ToArray();
return Activator.CreateInstance(implementationType, dependencies);
}
19
Source : ServiceProxy.cs
with Apache License 2.0
from grissomlau
with Apache License 2.0
from grissomlau
public T GetService<T>(JimuPayload payload = null) where T : clreplaced
{
//var instanceType = typeof(T);
var proxyType = _serviceProxyTypes.Single(typeof(T).GetTypeInfo().IsreplacedignableFrom);
var instance = proxyType.GetTypeInfo().GetConstructors().First().Invoke(new object[]
{
_remoteServiceCaller,
payload
});
return instance as T;
}
19
Source : UnityStorageLog.cs
with GNU General Public License v3.0
from grygus
with GNU General Public License v3.0
from grygus
private void SubscriveToEvent(EventInfo eventInfo, object targetObject, string targetMethod)
{
ConstructorInfo constructor = eventInfo.EventHandlerType.GetConstructors()[0];
Delegate handler = (Delegate)constructor.Invoke(new object[]
{
targetObject,
targetObject.GetType().GetMethod(targetMethod).MethodHandle.GetFunctionPointer()
});
eventInfo.AddEventHandler(null, handler);
}
19
Source : CacheLog.cs
with GNU General Public License v3.0
from grygus
with GNU General Public License v3.0
from grygus
private static void SubscriveToEvent(EventInfo eventInfo, object targetObject, string targetMethod)
{
ConstructorInfo constructor = eventInfo.EventHandlerType.GetConstructors()[0];
Delegate handler = (Delegate)constructor.Invoke(new object[]
{
null,
typeof(CacheLog).GetMethod(targetMethod, BindingFlags.Static | BindingFlags.NonPublic).MethodHandle.GetFunctionPointer()
});
eventInfo.AddEventHandler(null, handler);
}
19
Source : HarmonyExt.cs
with GNU General Public License v3.0
from gurrenm3
with GNU General Public License v3.0
from gurrenm3
public static void PatchPrefix<TClreplacedToPatch, TMyPatchClreplaced>(this HarmonyLib.Harmony harmonyInstance, int constructorIndex, string myPatchMethod)
{
var clreplacedToPatch = typeof(TClreplacedToPatch);
var myPatchClreplaced = typeof(TMyPatchClreplaced);
var constructor = clreplacedToPatch.GetConstructors()[constructorIndex];
harmonyInstance.Patch(constructor, prefix: new HarmonyMethod(AccessTools.Method(myPatchClreplaced, myPatchMethod)));
}
19
Source : HarmonyExt.cs
with GNU General Public License v3.0
from gurrenm3
with GNU General Public License v3.0
from gurrenm3
public static void PatchPostfix<TClreplacedToPatch, TMyPatchClreplaced>(this HarmonyLib.Harmony harmonyInstance, int constructorIndex, string myPatchMethod)
{
var clreplacedToPatch = typeof(TClreplacedToPatch);
var myPatchClreplaced = typeof(TMyPatchClreplaced);
var constructor = clreplacedToPatch.GetConstructors()[constructorIndex];
harmonyInstance.Patch(constructor, postfix: new HarmonyMethod(AccessTools.Method(myPatchClreplaced, myPatchMethod)));
}
19
Source : TypeExtensions.cs
with MIT License
from gustavopsantos
with MIT License
from gustavopsantos
internal static bool TryGetConstructors(this Type type, out ConstructorInfo[] constructors)
{
constructors = type.GetConstructors();
return constructors.Length > 0;
}
19
Source : Factory.cs
with MIT License
from gustavopsantos
with MIT License
from gustavopsantos
private void Start()
{
_e = new E();
_d = new D(_e);
_c = new C(_d);
_b = new B(_c);
_aConstructorInfo = typeof(A).GetConstructors().OrderByDescending(c => c.GetParameters().Length).First();
}
19
Source : ComponentProvider.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
private object Create(TypeInformation information)
{
Dictionary<ConstructorInfo, List<ConstructorParameter>> constructors = new Dictionary<ConstructorInfo, List<ConstructorParameter>>();
ConstructorInfo[] publicConstructors = information.InstanceType.GetConstructors();
if (publicConstructors.Length == 0)
throw new InvalidOperationException(information.InstanceType.FullName + " do not have any public constructors.");
foreach (var constructor in publicConstructors)
{
constructors.Add(constructor, new List<ConstructorParameter>());
foreach (var parameter in constructor.GetParameters())
{
ConstructorParameter constructorParameter = new ConstructorParameter {Parameter = parameter};
constructors[constructor].Add(constructorParameter);
TypeInformation typeInfo;
lock (_instances)
if (!_instances.TryGetValue(parameter.ParameterType, out typeInfo))
continue; // this constructor wont work, but check what parameters we are missing.
try
{
constructorParameter.Instance = typeInfo.Instance ?? Create(typeInfo);
}
catch(InvalidOperationException err)
{
throw new InvalidOperationException(
"Failed to create '" + typeInfo.InterfaceType.FullName + "' that '" + information.InterfaceType +
"' is dependent off. Check inner exception for more details.", err);
}
}
// check if all parameters was found.
bool allFound = true;
foreach (var parameter in constructors[constructor])
{
if (parameter.Instance != null) continue;
allFound = false;
break;
}
if (!allFound)
continue;
// now create instance.
information.ConstructorArguments = new object[constructors[constructor].Count];
int index = 0;
foreach (var parameter in constructors[constructor])
information.ConstructorArguments[index++] = parameter.Instance;
return Activator.CreateInstance(information.InstanceType, information.ConstructorArguments);
}
StringBuilder sb = new StringBuilder();
sb.AppendLine("Failed to create '" + information.InstanceType.FullName + "', due to missing constructorparamters.");
foreach (var pair in constructors)
{
sb.Append(pair.Key + " are missing: ");
foreach (var parameter in pair.Value)
{
if (parameter.Instance == null)
sb.Append(parameter.Parameter.Name + ", ");
}
sb.Length -= 2;
sb.AppendLine();
}
throw new InvalidOperationException(sb.ToString());
}
19
Source : SerializationTarget.cs
with Apache License 2.0
from HanJunJun
with Apache License 2.0
from HanJunJun
public static SerializationTarget Prepare( SerializationContext context, Type targetType )
{
VerifyCanSerializeTargetType( context, targetType );
IEnumerable<string> memberIgnoreList = context.BindingOptions.GetIgnoringMembers( targetType );
var getters = GetTargetMembers( targetType )
.Where( getter => !memberIgnoreList.Contains( getter.MemberName, StringComparer.Ordinal ) )
.OrderBy( entry => entry.Contract.Id )
.ToArray();
if ( getters.Length == 0
&& !typeof( IPackable ).IsreplacedignableFrom( targetType )
&& !typeof( IUnpackable ).IsreplacedignableFrom( targetType )
#if FEATURE_TAP
&& ( context.SerializerOptions.WithAsync
&& ( !typeof( IAsyncPackable ).IsreplacedignableFrom( targetType )
&& !typeof( IAsyncUnpackable ).IsreplacedignableFrom( targetType )
)
)
#endif // FEATURE_TAP
)
{
throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize type '{0}' because it does not have any serializable fields nor properties.", targetType ) );
}
var memberCandidates = getters.Where( entry => CheckTargetEligibility( context, entry.Member ) ).ToArray();
if ( memberCandidates.Length == 0 && !context.CompatibilityOptions.AllowAsymmetricSerializer )
{
ConstructorKind constructorKind;
var deserializationConstructor = FindDeserializationConstructor( context, targetType, out constructorKind );
var complementedMembers = ComplementMembers( getters, context, targetType );
var correspondingMemberNames = FindCorrespondingMemberNames( complementedMembers, deserializationConstructor );
return
new SerializationTarget(
complementedMembers,
deserializationConstructor,
correspondingMemberNames,
DetermineCanDeserialize( constructorKind, context, targetType, correspondingMemberNames, allowDefault: false )
);
}
else
{
bool? canDeserialize;
ConstructorKind constructorKind;
// Try to get default constructor.
var constructor = targetType.GetConstructor( ReflectionAbstractions.EmptyTypes );
if ( constructor == null && !targetType.GetIsValueType() )
{
// Try to get deserialization constructor.
var deserializationConstructor = FindDeserializationConstructor( context, targetType, out constructorKind );
if ( deserializationConstructor == null && !context.CompatibilityOptions.AllowAsymmetricSerializer )
{
throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructor( targetType );
}
constructor = deserializationConstructor;
canDeserialize = null;
}
else if ( memberCandidates.Length == 0 )
{
#if DEBUG
Contract.replacedert( context.CompatibilityOptions.AllowAsymmetricSerializer );
#endif // DEBUG
// Absolutely cannot deserialize in this case.
canDeserialize = false;
constructorKind = ConstructorKind.Ambiguous;
}
else
{
constructorKind = ConstructorKind.Default;
// Let's prefer annotated constructor here.
var markedConstructors = FindExplicitDeserializationConstructors( targetType.GetConstructors() );
if ( markedConstructors.Count == 1 )
{
// For backward compatibility, no exceptions are thrown here even if mulitiple deserialization constructor attributes in the type
// just use default constructor for it.
constructor = markedConstructors[ 0 ];
constructorKind = ConstructorKind.Marked;
}
// OK, appropriate constructor and setters are found.
canDeserialize = true;
}
if ( constructor != null && constructor.GetParameters().Any() || context.CompatibilityOptions.AllowAsymmetricSerializer )
{
// Recalculate members because getter-only/readonly members should be included for constructor deserialization.
memberCandidates = getters;
}
// Because members' order is equal to declared order is NOT guaranteed, so explicit ordering is required.
IList<SerializingMember> members;
if ( memberCandidates.All( item => item.Contract.Id == DataMemberContract.UnspecifiedId ) )
{
// Alphabetical order.
members = memberCandidates.OrderBy( item => item.Contract.Name ).ToArray();
}
else
{
// ID order.
members = ComplementMembers( memberCandidates, context, targetType );
}
var correspondingMemberNames = FindCorrespondingMemberNames( members, constructor );
return
new SerializationTarget(
members,
constructor,
correspondingMemberNames,
canDeserialize ?? DetermineCanDeserialize( constructorKind, context, targetType, correspondingMemberNames, allowDefault: true )
);
}
}
19
Source : SerializationTarget.cs
with Apache License 2.0
from HanJunJun
with Apache License 2.0
from HanJunJun
private static ConstructorInfo FindDeserializationConstructor( SerializationContext context, Type targetType, out ConstructorKind constructorKind )
{
var constructors = targetType.GetConstructors().ToArray();
if ( constructors.Length == 0 )
{
if ( context.CompatibilityOptions.AllowAsymmetricSerializer )
{
constructorKind = ConstructorKind.None;
return null;
}
else
{
throw NewTypeCannotBeSerializedException( targetType );
}
}
// The marked construtor is always preferred.
var markedConstructors = FindExplicitDeserializationConstructors( constructors );
switch ( markedConstructors.Count )
{
case 0:
{
break;
}
case 1:
{
// OK use it for deserialization.
constructorKind = ConstructorKind.Marked;
return markedConstructors[ 0 ];
}
default:
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"There are multiple constructors marked with MessagePackDeserializationConstrutorAttribute in type '{0}'.",
targetType
)
);
}
}
// A constructor which has most parameters will be used.
var mostRichConstructors =
constructors.GroupBy( ctor => ctor.GetParameters().Length ).OrderByDescending( g => g.Key ).First().ToArray();
#if DEBUG
Trace( "SerializationTarget::FindDeserializationConstructor.MostRich({0}) -> {1}", targetType, String.Join( ";", mostRichConstructors.Select( x => x.ToString() ).ToArray() ) );
#endif // DEBUG
switch ( mostRichConstructors.Length )
{
case 1:
{
if ( mostRichConstructors[ 0 ].GetParameters().Length == 0 )
{
if ( context.CompatibilityOptions.AllowAsymmetricSerializer )
{
constructorKind = ConstructorKind.Default;
return mostRichConstructors[ 0 ];
}
else
{
throw NewTypeCannotBeSerializedException( targetType );
}
}
// OK try use it but it may not handle deserialization correctly.
constructorKind = ConstructorKind.Parameterful;
return mostRichConstructors[ 0 ];
}
default:
{
if ( context.CompatibilityOptions.AllowAsymmetricSerializer )
{
constructorKind = ConstructorKind.Ambiguous;
return null;
}
else
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Cannot serialize type '{0}' because it does not have any serializable fields nor properties, and serializer generator failed to determine constructor to deserialize among({1}).",
targetType,
String.Join( ", ", mostRichConstructors.Select( ctor => ctor.ToString() ).ToArray() )
)
);
}
}
}
}
19
Source : SerializerEmitter.object.cs
with Apache License 2.0
from HanJunJun
with Apache License 2.0
from HanJunJun
public void DefineUnpackingContext( string name, IList<KeyValuePair<string, Type>> fields, out Type type, out ConstructorInfo constructor )
{
this._unpackingContextType =
this._host.DefineType(
this._typeBuilder.FullName + "_" + name,
TypeAttributes.Clreplaced | TypeAttributes.UnicodeClreplaced | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit
);
var parameterTypes = fields.Select( kv => kv.Value ).ToArray();
var ctor =
this._unpackingContextType.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
parameterTypes
);
var il = this.GetILGenerator( ctor, parameterTypes );
try
{
// call object.ctor
il.EmitLdargThis();
il.EmitCallConstructor( Metadata._Object.Ctor );
for ( var i = 0; i < fields.Count; i++ )
{
var field = this._unpackingContextType.DefineField( fields[ i ].Key, fields[ i ].Value, FieldAttributes.Public );
il.EmitLdargThis();
il.EmitAnyLdarg( i + 1 );
il.EmitStfld( field );
}
il.EmitRet();
}
finally
{
il.FlushTrace();
#if DEBUG
SerializerDebugging.FlushTraceData();
#endif // DEBUG
}
#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0
type = this._unpackingContextType.CreateType();
#else
type = this._unpackingContextType.CreateTypeInfo().AsType();
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0
constructor = type.GetConstructors().Single();
}
19
Source : UnpackHelpers.cs
with Apache License 2.0
from HanJunJun
with Apache License 2.0
from HanJunJun
private static ConstructorInfo TryGetCollectionConstructor( Type instanceType )
{
const int noParameters = 0;
const int withCapacity = 10;
const int withComparer = 11;
const int withComparerAndCapacity = 20;
const int withCapacityAndComparer = 21;
ConstructorInfo constructor = null;
var currentScore = -1;
foreach ( var candidate in instanceType.GetConstructors() )
{
var parameters = candidate.GetParameters();
switch ( parameters.Length )
{
case 0:
{
if ( currentScore < noParameters )
{
constructor = candidate;
currentScore = noParameters;
}
break;
}
case 1:
{
if ( currentScore < withCapacity && parameters[ 0 ].ParameterType == typeof( int ) )
{
constructor = candidate;
currentScore = noParameters;
}
else if ( currentScore < withComparer && IsIEqualityComparer( parameters[ 0 ].ParameterType ) )
{
constructor = candidate;
currentScore = noParameters;
}
break;
}
case 2:
{
if ( currentScore < withCapacityAndComparer && parameters[ 0 ].ParameterType == typeof( int ) && IsIEqualityComparer( parameters[ 1 ].ParameterType ) )
{
constructor = candidate;
currentScore = withCapacityAndComparer;
}
else if ( currentScore < withComparerAndCapacity && parameters[ 1 ].ParameterType == typeof( int ) && IsIEqualityComparer( parameters[ 0 ].ParameterType ) )
{
constructor = candidate;
currentScore = withComparerAndCapacity;
}
break;
}
}
}
return constructor;
}
19
Source : WrapperProcessor.cs
with MIT License
from Hertzole
with MIT License
from Hertzole
public static WrapperData CreateWrapper(TypeDefinition baseType, IReadOnlyList<IExposedProperty> properties)
{
if (baseType.HasNestedTypes)
{
for (int i = 0; i < baseType.NestedTypes.Count; i++)
{
if (baseType.NestedTypes[i].Name == WRAPPER_NAME)
{
throw new NotSupportedException($"{baseType.FullName} already has a nested clreplaced called '{WRAPPER_NAME}'.");
}
}
}
TypeDefinition wrapper = new TypeDefinition(baseType.Namespace, WRAPPER_NAME,
TypeAttributes.NestedPublic | TypeAttributes.SequentialLayout | TypeAttributes.AnsiClreplaced | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
baseType.Module.GetTypeReference<ValueType>());
baseType.NestedTypes.Add(wrapper);
wrapper.Interfaces.Add(new InterfaceImplementation(baseType.Module.GetTypeReference<IExposedWrapper>()));
TypeDefinition dirtyMaskType = CreateDirtyMask();
wrapper.NestedTypes.Add(dirtyMaskType);
FieldDefinition dirtyMaskField = new FieldDefinition("ALE__Generated__dirtyMaskField", FieldAttributes.Public, dirtyMaskType);
wrapper.Fields.Add(dirtyMaskField);
MethodDefinition ctor = wrapper.AddMethod(".ctor", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
ILProcessor il = ctor.BeginEdit();
ParameterDefinition dirtyMaskParameter = ctor.AddParameter(dirtyMaskType);
il.EmitLdarg();
il.EmitLdarg(dirtyMaskParameter);
il.Emit(OpCodes.Stfld, dirtyMaskField);
for (int i = 0; i < properties.Count; i++)
{
FieldDefinition field = CreateField(properties[i]);
wrapper.Fields.Add(field);
ParameterDefinition p = ctor.AddParameter(properties[i].FieldTypeComponentAware);
#if ALE_DEBUG
p.Name = properties[i].Name;
#else
#endif
#if ALE_DEBUG
il.Emit(OpCodes.Ldstr, $"{baseType.FullName} wrapper setting value for field {properties[i].Id} ({properties[i].Name})");
il.Emit(OpCodes.Call, baseType.Module.GetMethod(typeof(LevelEditorLogger), "Log", typeof(object)));
#endif
il.EmitLdarg();
il.EmitInt(properties[i].Id);
il.EmitLdarg(p);
MethodReference fieldCtor = baseType.Module.ImportReference(typeof(ValueTuple<,>)
.GetConstructors()
.Single(c => c.GetParameters().Length == 2))
.MakeHostInstanceGeneric(baseType.Module.ImportReference(typeof(ValueTuple<,>))
.MakeGenericInstanceType(baseType.Module.GetTypeReference<int>(), baseType.Module.ImportReference(properties[i].FieldTypeComponentAware)));
il.Emit(OpCodes.Newobj, fieldCtor);
il.Emit(OpCodes.Stfld, field);
}
il.Emit(OpCodes.Ret);
ctor.EndEdit();
return new WrapperData(wrapper, ctor, dirtyMaskType, dirtyMaskField);
TypeDefinition CreateDirtyMask()
{
TypeDefinition mask = new TypeDefinition(string.Empty, "ALE__GENERATED__dirtyMask", TypeAttributes.NestedPublic | TypeAttributes.AnsiClreplaced | TypeAttributes.Sealed, baseType.Module.GetTypeReference<Enum>());
mask.Fields.Add(new FieldDefinition("value__", FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName, baseType.Module.GetTypeReference<long>()));
FieldDefinition noneField = new FieldDefinition("None", FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal, mask)
{
Constant = 0L
};
mask.Fields.Add(noneField);
for (int i = 0; i < properties.Count; i++)
{
FieldDefinition field = new FieldDefinition(properties[i].Name, FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal, mask)
{
Constant = 1L << i
};
mask.Fields.Add(field);
}
return mask;
}
FieldDefinition CreateField(IExposedProperty property)
{
TypeReference tuple = baseType.Module.ImportReference(typeof(ValueTuple<,>)).MakeGenericInstanceType(baseType.Module.GetTypeReference<int>(), property.FieldTypeComponentAware);
FieldDefinition f = new FieldDefinition(property.Name, FieldAttributes.Public, tuple);
return f;
}
}
19
Source : CommandInvoker.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public virtual ConstructorInfo GetConstructor(Type type, CommandLineObjectPicker picker)
{
var constructors = type.GetConstructors();
if (constructors.Length == 0)
return null;
ConstructorInfo[] importDecorated = null;
//If we have a picker, look for a constructor that wants to run from the command line
if(picker != null)
importDecorated = constructors.Where(c => Attribute.IsDefined(c, typeof(UseWithCommandLineAttribute))).ToArray();
//otherwise look for a regular decorated constructor
if(importDecorated == null || !importDecorated.Any())
importDecorated = constructors.Where(c => Attribute.IsDefined(c, typeof(UseWithObjectConstructorAttribute))).ToArray();
if (importDecorated.Any())
return importDecorated[0];
return constructors[0];
}
19
Source : ObjectConstructor.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public ConstructorInfo GetRepositoryConstructor(Type type)
{
var compatible = new List<ConstructorInfo>();
foreach (var constructorInfo in type.GetConstructors())
{
var parameters = constructorInfo.GetParameters();
//don't use this constructor
if (parameters.Any(p => p.GetType() == typeof(ShareManager)))
continue;
//this is for fetching existing instances
if (parameters.Any(p => p.GetType() == typeof(DbDataReader)))
continue;
//at least one parameter must be an IRepository
if(!parameters.Any(p=>typeof(IRepository).IsreplacedignableFrom(p.ParameterType)))
continue;
//yay it's compatible
compatible.Add(constructorInfo);
}
if (compatible.Count == 1)
return compatible.Single();
throw new ObjectLacksCompatibleConstructorException("No best constructor found for Type " + type +" (found " + compatible.Count +")");
}
See More Examples