Here are the examples of the csharp api System.Type.GetTypeInfo() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4949 Examples
19
Source : ScInsertCompanies.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private IEnumerable<JsonCompanyData> ReadCompanyData()
{
var replacedembly = typeof(Program).GetTypeInfo().replacedembly;
using Stream? resource = replacedembly.GetManifestResourceStream("SqExpress.IntTest.TestData.company.json");
var doreplacedent = JsonDoreplacedent.Parse(resource);
foreach (var user in doreplacedent.RootElement.EnumerateArray())
{
JsonCompanyData buffer = default;
foreach (var userProperty in user.EnumerateObject())
{
if (userProperty.Name == "external_id")
{
buffer.ExternalId = userProperty.Value.GetGuid();
}
if (userProperty.Name == "name")
{
buffer.Name = userProperty.Value.GetString();
}
}
yield return buffer;
}
}
19
Source : ScInsertUserData.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private IEnumerable<JsonUserData> ReadUserData()
{
var replacedembly = typeof(Program).GetTypeInfo().replacedembly;
using Stream? resource = replacedembly.GetManifestResourceStream("SqExpress.IntTest.TestData.users.json");
var doreplacedent = JsonDoreplacedent.Parse(resource);
foreach (var user in doreplacedent.RootElement.EnumerateArray())
{
JsonUserData buffer = default;
foreach (var userProperty in user.EnumerateObject())
{
if (userProperty.Name == "external_id")
{
buffer.ExternalId = userProperty.Value.GetGuid();
}
if (userProperty.Name == "first_name")
{
buffer.FirstName = userProperty.Value.GetString();
}
if (userProperty.Name == "last_name")
{
buffer.LastName = userProperty.Value.GetString();
}
if (userProperty.Name == "email")
{
buffer.Email = userProperty.Value.GetString();
}
}
yield return buffer;
}
}
19
Source : ProxyGenerator.cs
with MIT License
from 1100100
with MIT License
from 1100100
public static List<Type> GenerateProxy(List<Type> interfaces)
{
if (interfaces.Any(p => !p.IsInterface && !typeof(IService).IsreplacedignableFrom(p)))
throw new ArgumentException("The proxy object must be an interface and inherit IService.", nameof(interfaces));
var replacedemblies = DependencyContext.Default.RuntimeLibraries.SelectMany(i => i.GetDefaultreplacedemblyNames(DependencyContext.Default).Select(z => replacedembly.Load(new replacedemblyName(z.Name)))).Where(i => !i.IsDynamic);
var types = replacedemblies.Select(p => p.GetType()).Except(interfaces);
replacedemblies = types.Aggregate(replacedemblies, (current, type) => current.Append(type.replacedembly));
var trees = interfaces.Select(GenerateProxyTree).ToList();
if (UraganoOptions.Output_DynamicProxy_SourceCode.Value)
{
for (var i = 0; i < trees.Count; i++)
{
File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), $"{interfaces[i].Name}.Implement.cs"),
trees[i].ToString());
}
}
using (var stream = CompileClientProxy(trees,
replacedemblies.Select(x => MetadataReference.CreateFromFile(x.Location))
.Concat(new[]
{
MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().replacedembly.Location)
})))
{
var replacedembly = replacedemblyLoadContext.Default.LoadFromStream(stream);
return replacedembly.GetExportedTypes().ToList();
}
}
19
Source : ProxyGenerator.cs
with MIT License
from 1100100
with MIT License
from 1100100
private static MemoryStream CompileClientProxy(IEnumerable<SyntaxTree> trees, IEnumerable<MetadataReference> references)
{
var replacedemblies = new[]
{
"System.Runtime",
"mscorlib",
"System.Threading.Tasks",
"System.Collections"
};
references = replacedemblies.Select(i => MetadataReference.CreateFromFile(replacedembly.Load(new replacedemblyName(i)).Location)).Concat(references);
references = references.Concat(new[]
{
MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(typeof(DynamicProxyAbstract).GetTypeInfo().replacedembly.Location)
});
return Compile("Uragano.DynamicProxy.UraganoProxy", trees, references);
}
19
Source : VerifyHelper.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static T Is<T>(this T actual, T expected)
{
if (expected == null)
{
replacedert.Null(actual);
return actual;
}
if (typeof(T) != typeof(string) && typeof(IEnumerable).GetTypeInfo().IsreplacedignableFrom(typeof(T)))
{
replacedert.Equal(
((IEnumerable)expected).Cast<object>().ToArray(),
((IEnumerable)actual).Cast<object>().ToArray());
return actual;
}
replacedert.Equal(expected, actual);
return actual;
}
19
Source : EventHandlerBehavior.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
private void RegisterEvent(string eventName)
{
if (string.IsNullOrWhiteSpace(eventName))
{
return;
}
var sourceObjectType = _resolvedSource.GetType();
var eventInfo = sourceObjectType.GetRuntimeEvent(eventName);
if (eventInfo is null)
{
return;
}
var methodInfo = typeof(EventHandlerBehavior).GetTypeInfo().GetDeclaredMethod("OnEvent");
_eventHandler = methodInfo.CreateDelegate(eventInfo.EventHandlerType, this);
eventInfo.AddEventHandler(_resolvedSource, _eventHandler);
}
19
Source : App.xaml.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
var replacedembliesToInclude = new List<replacedembly> {typeof(SegmentedControlRenderer).GetTypeInfo().replacedembly};
Xamarin.Forms.Forms.Init(e, replacedembliesToInclude);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by preplaceding required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
19
Source : InvokeMethodAction.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
private MethodDescriptor FindBestMethod(object parameter)
{
var parameterTypeInfo = parameter?.GetType().GetTypeInfo();
if (parameterTypeInfo is null)
{
return _cachedMethodDescriptor;
}
MethodDescriptor mostDerivedMethod = null;
foreach (var currentMethod in _methodDescriptors)
{
var currentTypeInfo = currentMethod.SecondParameterTypeInfo;
if (currentTypeInfo.IsreplacedignableFrom(parameterTypeInfo))
{
if (mostDerivedMethod is null || !currentTypeInfo.IsreplacedignableFrom(mostDerivedMethod.SecondParameterTypeInfo))
{
mostDerivedMethod = currentMethod;
}
}
}
return mostDerivedMethod ?? _cachedMethodDescriptor;
}
19
Source : SetPropertyAction.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
private void UpdatePropertyValue(object targetObject)
{
var targetType = targetObject.GetType();
var propertyInfo = targetType.GetRuntimeProperty(PropertyName);
ValidateProperty(targetType.Name, propertyInfo);
Exception innerException = null;
try
{
object result;
var propertyType = propertyInfo.PropertyType;
var propertyTypeInfo = propertyType.GetTypeInfo();
if (Value is null)
{
result = propertyTypeInfo.IsValueType ? Activator.CreateInstance(propertyType) : null;
}
else if (propertyTypeInfo.IsreplacedignableFrom(Value.GetType().GetTypeInfo()))
{
result = Value;
}
else
{
var valuereplacedtring = Value.ToString();
result = propertyTypeInfo.IsEnum ? Enum.Parse(propertyType, valuereplacedtring, false) : TypeConverterHelper.Convert(valuereplacedtring, propertyType.FullName);
}
propertyInfo.SetValue(targetObject, result, new object[0]);
}
catch (FormatException ex)
{
innerException = ex;
}
catch (ArgumentException ex)
{
innerException = ex;
}
if (innerException != null)
{
throw new ArgumentException("Cannot set value.", innerException);
}
}
19
Source : SourceSymbolFactory.cs
with MIT License
from 71
with MIT License
from 71
private static object Invoke(int key, Type type, string methodName, params object[] args)
{
if (CachedFuncs.TryGetValue(key, out var func))
return func(args);
// ReSharper disable once CoVariantArrayConversion
MethodInfo method = (MethodInfo)Proxy.FindMatchingMethod(type.GetMethods(Proxy.ALL), methodName, args);
ParameterInfo[] parameters = method.GetParameters();
func = Helpers.MakeDelegate<Func<object[], object>>(methodName, il =>
{
for (int i = 0; i < parameters.Length; i++)
{
Type paramType = parameters[i].ParameterType;
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldelem_Ref);
if (paramType == typeof(object))
continue;
il.Emit(paramType.GetTypeInfo().IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclreplaced, paramType);
}
il.Emit(OpCodes.Call, method);
il.Emit(OpCodes.Castclreplaced, method.ReturnType);
il.Emit(OpCodes.Ret);
}, type);
CachedFuncs.Add(key, func);
return func(args);
}
19
Source : InvokeEditor.cs
with MIT License
from 71
with MIT License
from 71
private void VisitSymbol(ISymbol symbol)
{
// Only check methods
if (!(symbol is IMethodSymbol method))
return;
// Find Invoke attribute
var attr = method.GetAttributes().FirstOrDefault(x => x.AttributeClreplaced.Name == nameof(InvokeAttribute));
if (attr == null)
// No attribute found, return
return;
// We have the attribute, find its matching method
var info = method.GetCorrespondingMethod() as MethodInfo;
if (info == null)
{
ReportWarning("Cannot invoke given method", symbol.Locations[0]);
return;
}
// Check method
if (!method.IsStatic)
throw new DiagnosticException("A compile-time function must be static.", symbol.Locations[0]);
if (method.IsAbstract)
throw new DiagnosticException("A compile-time function cannot be abstract.", symbol.Locations[0]);
if (method.ReturnType.MetadataName != "Void")
ReportWarning("A compile-time function should return void.", symbol.Locations[0]);
// Populate args
ParameterInfo[] parameters = info.GetParameters();
object[] arguments = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
ParameterInfo parameter = parameters[i];
TypeInfo parameterType = parameter.ParameterType.GetTypeInfo();
if (parameterType.IsreplacedignableFrom(typeof(IMethodSymbol).GetTypeInfo()))
arguments[i] = method;
else if (parameterType.IsreplacedignableFrom(typeof(MethodInfo).GetTypeInfo()))
arguments[i] = info;
else if (parameter.ParameterType.IsreplacedignableFrom(typeof(ITypeSymbol)))
arguments[i] = symbol.ContainingType;
else if (parameter.ParameterType == typeof(TypeInfo))
arguments[i] = info.DeclaringType.GetTypeInfo();
else if (parameter.ParameterType == typeof(Type))
arguments[i] = info.DeclaringType;
}
// Invoke and return
try
{
info.Invoke(null, arguments);
}
catch (Exception e)
{
ReportError(e.Message, symbol.Locations[0]);
}
}
19
Source : Proxy.cs
with MIT License
from 71
with MIT License
from 71
internal static MethodBase FindMatchingMethod(MethodBase[] possibleMethods, string name, params object[] args)
{
for (int i = 0; i < possibleMethods.Length; i++)
{
MethodBase mi = possibleMethods[i];
if (mi.Name != name)
continue;
// Same name, but do the parameters match?
ParameterInfo[] parameters = mi.GetParameters();
if (parameters.Length != args.Length)
continue;
for (int j = 0; j < parameters.Length; j++)
{
object arg = args[j];
ParameterInfo parameter = parameters[j];
if (arg == null)
{
if (parameter.ParameterType.GetTypeInfo().IsValueType)
goto Nope;
continue;
}
if (!parameter.ParameterType.IsInstanceOfType(arg))
goto Nope;
}
return mi;
Nope:;
}
return null;
}
19
Source : Helpers.cs
with MIT License
from 71
with MIT License
from 71
internal static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
do
{
foreach (FieldInfo field in type.GetRuntimeFields())
yield return field;
type = type.GetTypeInfo().BaseType;
}
while (type != null);
}
19
Source : Helpers.cs
with MIT License
from 71
with MIT License
from 71
internal static Type FindCommonType(Type a, Type b)
{
List<Type> aMap = new List<Type>();
List<Type> bMap = new List<Type>();
while (a != typeof(Compilation))
{
aMap.Insert(0, a);
a = a.GetTypeInfo().BaseType;
}
while (b != typeof(Compilation))
{
bMap.Insert(0, b);
b = b.GetTypeInfo().BaseType;
}
for (int i = 1; i < Math.Min(aMap.Count, bMap.Count); i++)
{
if (aMap[i] != bMap[i])
return aMap[i - 1];
}
return typeof(Compilation);
}
19
Source : Helpers.cs
with MIT License
from 71
with MIT License
from 71
internal static void CopyTo<T>(this T from, T to) where T : clreplaced
{
// Find base type of both compilations
TypeInfo fromType = from.GetType().GetTypeInfo();
TypeInfo toType = to.GetType().GetTypeInfo();
Type baseType;
if (fromType.IsreplacedignableFrom(toType))
{
// ToCompilation inherits FromCompilation
baseType = fromType.AsType();
}
else if (toType.IsreplacedignableFrom(fromType))
{
// FromCompilation inherits ToCompilation
baseType = toType.AsType();
}
else
{
// No common type: find first common type
baseType = FindCommonType(fromType.AsType(), toType.AsType());
}
// Copy fields from one compilation to the other
foreach (FieldInfo field in baseType.GetAllFields())
{
if (field.IsStatic)
continue;
field.SetValue(to, field.GetValue(from));
}
}
19
Source : ForEachExpression.cs
with MIT License
from 71
with MIT License
from 71
private Expression ReduceForEnumerable()
{
MethodInfo get_enumerator;
MethodInfo get_current;
ResolveEnumerationMembers(out get_enumerator, out get_current);
Type enumerator_type = get_enumerator.ReturnType;
ParameterExpression enumerator = Variable(enumerator_type);
LabelTarget inner_loop_continue = Label("inner_loop_continue");
LabelTarget inner_loop_break = Label("inner_loop_break");
LabelTarget @continue = ContinueLabel ?? Label("continue");
LabelTarget @break = BreakLabel ?? Label("break");
Expression variable_initializer = Property(enumerator, get_current);
if (!Variable.Type.GetTypeInfo().IsreplacedignableFrom(get_current.ReturnType.GetTypeInfo()))
variable_initializer = Convert(variable_initializer, Variable.Type);
Expression loop = Block(
new [] { Variable },
Goto(@continue),
Loop(
Block(
replacedign(Variable, variable_initializer),
Body,
Label(@continue),
Condition(
Call(enumerator, Reflection.IEnumerator_MoveNext),
Goto(inner_loop_continue),
Goto(inner_loop_break)
)
),
inner_loop_break,
inner_loop_continue
),
Label(@break)
);
Expression dispose = CreateDisposeOperation(enumerator_type.GetTypeInfo(), enumerator);
return Block(
new [] { enumerator },
replacedign(enumerator, Call(Enumerable, get_enumerator)),
dispose != null ? TryFinally(loop, dispose) : loop
);
}
19
Source : ForEachExpression.cs
with MIT License
from 71
with MIT License
from 71
private bool TryGetGenericEnumerableArgument (out Type argument)
{
argument = null;
foreach (var iface in Enumerable.Type.GetTypeInfo().ImplementedInterfaces)
{
if (iface.GenericTypeArguments.Length == 0)
continue;
var definition = iface.GetGenericTypeDefinition();
if (definition != typeof(IEnumerable<>))
continue;
argument = iface.GenericTypeArguments[0];
if (Variable.Type.GetTypeInfo().IsreplacedignableFrom(argument.GetTypeInfo()))
return true;
}
return false;
}
19
Source : ExpressionVisitor`1.cs
with MIT License
from 71
with MIT License
from 71
protected void EnableDynamicVisiting()
{
if (dynamicVisit != null)
return;
Type returnType = typeof(T);
ParameterExpression exprParam = Expression.Parameter(typeof(Expression), "node");
Expression body = Expression.Call(Expression.Constant(this), nameof(DefaultVisit), null, exprParam);
foreach (MethodInfo method in this.GetType().GetTypeInfo().DeclaredMethods)
{
if (method.ReturnType != returnType || !method.Name.StartsWith("Visit"))
continue;
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 1)
continue;
ParameterInfo parameter = parameters[0];
if (!parameter.ParameterType.IsreplacedignableTo(typeof(Expression)))
continue;
// We got this far, it's a valid Visit*() method.
ParameterExpression exprVar = Expression.Parameter(parameter.ParameterType, parameter.Name);
// expr is TExpr newExpr ? newExpr : body
body = Expression.Block(new[] { exprVar },
Expression.replacedign(exprVar, Expression.TypeAs(exprParam, parameter.ParameterType)),
Expression.Condition(
Expression.ReferenceNotEqual(exprVar, Expression.Constant(null)),
exprVar,
body
)
);
}
dynamicVisit = Expression.Lambda<Func<Expression, T>>(body, exprParam).Compile();
}
19
Source : CometaryExtensions.cs
with MIT License
from 71
with MIT License
from 71
public static IEnumerable<T> FindAttributesOfInterface<T>(this ImmutableArray<AttributeData> attributes)
{
Type interfType = typeof(T);
if (!interfType.GetTypeInfo().IsInterface)
throw new ArgumentException("Expected an interface.");
string metadataName = interfType.IsConstructedGenericType
? interfType.GetGenericTypeDefinition().FullName
: interfType.FullName;
for (int i = 0; i < attributes.Length; i++)
{
AttributeData data = attributes[i];
ImmutableArray<INamedTypeSymbol> interfaces = data.AttributeClreplaced.AllInterfaces;
for (int o = 0; o < interfaces.Length; o++)
{
INamedTypeSymbol interf = interfaces[o];
if (interf.MetadataName != metadataName)
continue;
// We got this far, so we have a valid attribute; construct it.
yield return data.Construct<T>();
break;
}
}
}
19
Source : Proxy.cs
with MIT License
from 71
with MIT License
from 71
public bool TryGet(string name, out object result)
{
object obj = Object;
// Compute key, and try to find an already computed delegate
int key = Combine(ObjectTypeHash, name.GetHashCode());
if (data.Getters.TryGetValue(key, out var del))
{
result = del(obj);
return true;
}
// Nothing already computed, compute it now
PropertyInfo prop = obj.GetType().GetProperty(name, ALL);
if (prop == null)
{
result = null;
return false;
}
data.Getters[key] = del = Helpers.MakeDelegate<Func<object, object>>(name, il =>
{
if (!(prop.GetMethod ?? prop.SetMethod).IsStatic)
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, prop.GetMethod);
if (prop.PropertyType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Box, prop.PropertyType);
il.Emit(OpCodes.Ret);
});
result = del(obj);
return true;
}
19
Source : Proxy.cs
with MIT License
from 71
with MIT License
from 71
public bool TrySet(string name, object value)
{
// Compute key, and try to find an already computed delegate
int key = Combine(ObjectTypeHash, name.GetHashCode());
if (data.Setters.TryGetValue(key, out var del))
{
del(Object, value);
return true;
}
// Nothing already computed, compute it now
PropertyInfo prop = ObjectType.GetProperty(name, ALL);
if (prop == null)
return false;
data.Setters[key] = Helpers.MakeDelegate<Func<object, object, object>>(name, il =>
{
if ((prop.GetMethod ?? prop.SetMethod).IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
}
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
}
if (prop.PropertyType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Unbox_Any);
else if (prop.PropertyType != typeof(object))
il.Emit(OpCodes.Castclreplaced, prop.PropertyType);
il.Emit(OpCodes.Call, prop.SetMethod);
if (prop.PropertyType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Box, prop.PropertyType);
il.Emit(OpCodes.Ret);
});
return true;
}
19
Source : AwaitExpression.cs
with MIT License
from 71
with MIT License
from 71
public static AwaitExpression Await(Expression task, MethodInfo method)
{
Requires.NotNull(task, nameof(task));
if (method == null)
return Await(task);
if (method.ReturnType != typeof(TaskAwaiter)
&& method.ReturnType.GetGenericTypeDefinition() != typeof(TaskAwaiter<>))
throw new ArgumentException("Method does not return a TaskAwaiter.", nameof(method));
ParameterInfo[] parameters = method.GetParameters();
if (method.IsStatic)
{
if (parameters.Length != 1 || parameters[0].ParameterType.GetTypeInfo().IsreplacedignableFrom(task.Type.GetTypeInfo()))
throw new ArgumentException("Invalid method signature.", nameof(method));
}
else
{
if (parameters.Length != 0)
throw new ArgumentException("Invalid method signature.", nameof(method));
}
return new AwaitExpression(task, method);
}
19
Source : IteratorExpression.cs
with MIT License
from 71
with MIT License
from 71
private Type DeduceItemType()
{
Type commonType = _yields[0].Type;
for (int i = 1; i < _yields.Count; i++)
{
Type yieldType = _yields[i].Type;
while (!yieldType.IsreplacedignableTo(commonType))
yieldType = commonType.GetTypeInfo().BaseType;
}
return commonType;
}
19
Source : StateMachineExpression.cs
with MIT License
from 71
with MIT License
from 71
protected void SetType(Type lambdaType, Type smType)
{
Requires.NotNull(lambdaType, nameof(lambdaType));
Requires.NotNull(smType, nameof(smType));
_type = lambdaType;
_end = Label(lambdaType, "end");
_state = Parameter(smType, "state");
_vsmCtor = smType.GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0);
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static IEnumerable<MethodInfo> GetMethods(this TypeInfo type, string name)
{
return type.BaseType == null
? type.GetDeclaredMethods(name)
: type.GetDeclaredMethods(name).Concat(type.BaseType.GetTypeInfo().GetMethods(name));
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static bool IsreplacedignableTo<T>(this Expression expr)
{
return typeof(T).GetTypeInfo().IsreplacedignableFrom(expr.Type.GetTypeInfo());
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static Type GereplacedemType(Expression enumerable)
{
Type type = enumerable.Type;
if (type.IsArray)
return type.GetElementType();
TypeInfo enumerableTypeInfo = typeof(IEnumerable<>).GetTypeInfo();
TypeInfo typeInfo = type.GetTypeInfo();
foreach (var iface in typeInfo.ImplementedInterfaces)
{
if (enumerableTypeInfo.IsreplacedignableFrom(iface.GetTypeInfo()))
{
return iface.GenericTypeArguments[0];
}
}
return typeof(object);
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static bool IsCompilerGenerated(this Type type)
{
return type.GetTypeInfo().IsCompilerGenerated();
}
19
Source : SourceSymbolFactory.cs
with MIT License
from 71
with MIT License
from 71
private static object Invoke(int key, Type type, params object[] args)
{
if (CachedCtors.TryGetValue(key, out var func))
return func(args);
// ReSharper disable once CoVariantArrayConversion
ConstructorInfo ctor = (ConstructorInfo)Proxy.FindMatchingMethod(type.GetConstructors(Proxy.ALL), ".ctor", args);
ParameterInfo[] parameters = ctor.GetParameters();
func = Helpers.MakeDelegate<Func<object[], object>>("ctor", il =>
{
for (int i = 0; i < parameters.Length; i++)
{
Type paramType = parameters[i].ParameterType;
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldelem_Ref);
if (paramType == typeof(object))
continue;
il.Emit(paramType.GetTypeInfo().IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclreplaced, paramType);
}
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Ret);
}, type);
CachedCtors.Add(key, func);
return func(args);
}
19
Source : DebuggingEditor.cs
with MIT License
from 71
with MIT License
from 71
private static SourceText GetSourceText(bool breaking, string errorFile)
{
using (Stream templateStream = typeof(DebuggingEditor).GetTypeInfo().replacedembly.GetManifestResourceStream("Cometary.Debugging.DebugProgramTemplate.cs"))
using (TextReader reader = new StreamReader(templateStream, Encoding.UTF8))
{
return breaking
? SourceText.From(reader.ReadToEnd().Replace("%ERRORFILE%", errorFile), Encoding.UTF8)
: SourceText.From(reader.ReadToEnd(), Encoding.UTF8);
}
}
19
Source : ForEachExpression.cs
with MIT License
from 71
with MIT License
from 71
private void ResolveEnumerationMembers (
out MethodInfo get_enumerator,
out MethodInfo get_current)
{
Type item_type;
Type enumerable_type;
Type enumerator_type;
if (TryGetGenericEnumerableArgument(out item_type))
{
enumerable_type = typeof(IEnumerable<>).MakeGenericType(item_type);
enumerator_type = typeof(IEnumerator<>).MakeGenericType(item_type);
}
else
{
enumerable_type = typeof(IEnumerable);
enumerator_type = typeof(IEnumerator);
}
get_current = enumerator_type.GetRuntimeProperty(nameof(IEnumerator<object>.Current)).GetMethod;
get_enumerator = Enumerable.Type.GetRuntimeMethod("GetEnumerator", Type.EmptyTypes);
if (get_enumerator == null || !enumerator_type.GetTypeInfo().IsreplacedignableFrom(get_enumerator.ReturnType.GetTypeInfo()))
get_enumerator = enumerable_type.GetRuntimeMethod("GetEnumerator", Type.EmptyTypes);
}
19
Source : CometaryExtensions.cs
with MIT License
from 71
with MIT License
from 71
public static IEnumerable<T> FindAttributesOfType<T>(this ImmutableArray<AttributeData> attributes, bool allowInherited = true)
{
Type type = typeof(T);
if (type.GetTypeInfo().IsInterface)
throw new ArgumentException("Expected a type.");
string metadataName = type.IsConstructedGenericType
? type.GetGenericTypeDefinition().Name
: type.Name;
for (int i = 0; i < attributes.Length; i++)
{
AttributeData data = attributes[i];
ITypeSymbol typeSymbol = data.AttributeClreplaced;
if (!allowInherited && typeSymbol.MetadataName == metadataName)
{
yield return data.Construct<T>();
}
else if (allowInherited)
{
while (typeSymbol != null)
{
if (typeSymbol.MetadataName == metadataName)
{
yield return data.Construct<T>();
break;
}
typeSymbol = typeSymbol.BaseType;
}
}
}
}
19
Source : CometaryExtensions.cs
with MIT License
from 71
with MIT License
from 71
public static IEnumerable<T> FindAttributes<T>(this ImmutableArray<AttributeData> attributes)
{
return typeof(T).GetTypeInfo().IsInterface
? attributes.FindAttributesOfInterface<T>()
: attributes.FindAttributesOfType<T>();
}
19
Source : VirtualStateMachine.cs
with MIT License
from 71
with MIT License
from 71
public virtual void Reset()
{
_state = NOT_YET_STARTED;
for (int i = 0; i < _locals.Length; i++)
{
object ith = _locals[i];
_locals[i] = ith == null || !ith.GetType().GetTypeInfo().IsValueType
? null : Activator.CreateInstance(ith.GetType());
}
Initialize();
}
19
Source : VirtualStateMachine.cs
with MIT License
from 71
with MIT License
from 71
internal void Initialize(ParameterExpression[] locals, int endState, Delegate next)
{
_locals = new object[locals.Length];
_readOnlyLocals = new ReadOnlyCollection<object>(_locals);
_endState = endState;
_next = next;
for (int i = 0; i < locals.Length; i++)
{
Type localType = locals[i].Type;
_locals[i] = localType.GetTypeInfo().IsValueType ? Activator.CreateInstance(localType) : null;
}
Initialize();
}
19
Source : LockExpression.cs
with MIT License
from 71
with MIT License
from 71
public static LockExpression Lock(Expression obj, Expression body)
{
Requires.NotNull(obj, nameof(obj));
Requires.NotNull(body, nameof(body));
if (obj.Type.GetTypeInfo().IsValueType)
throw new ArgumentException("The given argument must be a reference type.", nameof(obj));
return new LockExpression(obj, body);
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static bool IsreplacedignableTo(this Expression expr, Type type)
{
return type.GetTypeInfo().IsreplacedignableFrom(expr.Type.GetTypeInfo());
}
19
Source : Redirection.Reactive.cs
with MIT License
from 71
with MIT License
from 71
private static MethodRedirection CreateDynamicRedirection(MethodBase method, out int id)
{
// Make id
do
{
id = ObservingRedirectionsIdGenerator.Next();
}
while (ObservingRedirections.ContainsKey(id));
// Creates an array containing all parameter types
int diff = method.IsStatic ? 0 : 1;
ParameterInfo[] originalParameters = method.GetParameters();
Type[] originalParameterTypes = new Type[originalParameters.Length + diff];
if (diff == 1 /* !method.IsStatic */)
originalParameterTypes[0] = method.DeclaringType;
for (int i = 0; i < originalParameters.Length; i++)
{
originalParameterTypes[i + diff] = originalParameters[i].ParameterType;
}
// Create an identical method
bool isCtor = method is ConstructorInfo;
Type returnType = isCtor ? typeof(void) : ((MethodInfo)method).ReturnType;
DynamicMethod dyn = new DynamicMethod(
name: method.Name,
attributes: MethodAttributes.Public | MethodAttributes.Static,
callingConvention: CallingConventions.Standard,
returnType: returnType,
parameterTypes: originalParameterTypes,
owner: method.DeclaringType,
skipVisibility: true);
// Make the method call the observable
ILGenerator il = dyn.GetILGenerator();
{
// This is in a block to make every more readable,
// the following comments describe what's happening in the generated method.
// Emit "this", or "null"
if (method.IsStatic)
{
il.Emit(OpCodes.Ldnull);
}
else
{
il.Emit(OpCodes.Ldarg_0);
if (method.DeclaringType.GetTypeInfo().IsValueType)
{
il.Emit(OpCodes.Ldobj, method.DeclaringType);
il.Emit(OpCodes.Box, method.DeclaringType);
}
}
// Create an array containing all parameters
il.Emit(OpCodes.Ldc_I4, originalParameters.Length);
il.Emit(OpCodes.Newarr, typeof(object));
for (int i = 0; i < originalParameters.Length; i++)
{
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldarg, i + diff);
Type parameterType = originalParameterTypes[i + diff];
if (parameterType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Box, parameterType);
il.Emit(OpCodes.Stelem_Ref);
}
// Array is still on stack (thanks to dup)
// Emit id
il.Emit(OpCodes.Ldc_I4, id);
// Call "hook" method
il.Emit(OpCodes.Call, typeof(Redirection).GetMethod(nameof(OnInvoked), BindingFlags.Static | BindingFlags.NonPublic));
// Return returned result
// (But first, cast it if needed)
if (returnType == typeof(void))
il.Emit(OpCodes.Pop);
else if (returnType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Unbox_Any, returnType);
else if (returnType != typeof(object))
il.Emit(OpCodes.Castclreplaced, returnType);
il.Emit(OpCodes.Ret);
}
// Return the redirection
return new MethodRedirection(method, dyn, false);
}
19
Source : Ryder.Lightweight.cs
with MIT License
from 71
with MIT License
from 71
public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
{
// First, try the good ol' RuntimeHelpers.PrepareMethod.
if (PrepareMethod != null)
{
PrepareMethod(handle);
return true;
}
// No chance, we gotta go lower.
// Invoke the method with uninitialized arguments.
object sender = null;
object[] GetArguments(ParameterInfo[] parameters)
{
object[] args = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
ParameterInfo param = parameters[i];
if (param.HasDefaultValue)
args[i] = param.DefaultValue;
else if (param.ParameterType.GetTypeInfo().IsValueType)
args[i] = Activator.CreateInstance(param.ParameterType);
else
args[i] = null;
}
return args;
}
if (!method.IsStatic)
{
// Gotta make the instance
Type declaringType = method.DeclaringType;
if (declaringType.GetTypeInfo().IsValueType)
{
sender = Activator.CreateInstance(declaringType);
}
else if (declaringType.GetTypeInfo().IsAbstract)
{
// Overkill solution: Find a type in the replacedembly that implements the declaring type,
// and use it instead.
throw new InvalidOperationException("Cannot manually JIT a method");
}
else if (GetUninitializedObject != null)
{
sender = GetUninitializedObject(declaringType);
}
else
{
/* TODO
* Since I just made the whole 'gotta JIT the method' step mandatory
* in the MethodRedirection ctor, i should make sure this always returns true.
* That means looking up every type for overriding types for the throwing step above,
* and testing every possible constructor to create the instance.
*
* Additionally, if we want to go even further, we can repeat this step for every
* single argument of the ctor, thus making sure that we end up having an actual clreplaced.
* In this case, unless the user wants to instantiate an abstract clreplaced with no overriding clreplaced,
* everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
* may mean scanning the replacedembly a dozen times for overriding types, calling their constructors
* hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
* perfs-friendly).
*/
ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);
if (ctor != null)
{
sender = ctor.Invoke(null);
}
else
{
ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);
Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));
ctor = ctors[0];
try
{
sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
}
catch (TargetInvocationException)
{
// Nothing we can do, give up.
return false;
}
}
}
}
try
{
method.Invoke(sender, GetArguments(method.GetParameters()));
}
catch (TargetInvocationException)
{
// That's okay.
}
return true;
}
19
Source : HelpersTests.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void TestUninitializedMethods()
{
bool IsValidMethod(MethodInfo method)
{
if (method.IsAbstract)
return false;
if (!method.IsStatic && method.DeclaringType.GetTypeInfo().IsAbstract)
return false;
return !method.ContainsGenericParameters;
}
// We're testing LINQ expressions here, cuz there are (instance / static) and (public / non-public) methods,
// properties, and most methods are independant. Last time I checked, running this step checks
// 193 different methods.
foreach (var method in typeof(Expression).GetMethods(BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic)
.Where(IsValidMethod)
.GroupBy(x => x.Name)
.Select(Enumerable.First))
{
// Find non-jitted start
IntPtr start = method.GetRuntimeMethodHandle().GetMethodStart();
// Compile method (should work on this platform)
Helpers.TryPrepareMethod(method, method.GetRuntimeMethodHandle()).ShouldBeTrue();
// Find freshly jitted start
IntPtr newStart = method.GetRuntimeMethodHandle().GetMethodStart();
// start != newStart => it wasn't jitted before: Fixup should be good
start.HasBeenCompiled().ShouldBe(start == newStart);
// In any case, the new method shouldn't be a fixup
newStart.HasBeenCompiled().ShouldBeTrue();
}
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static IEnumerable<MemberInfo> GetMembers(this Type type)
{
return type.GetTypeInfo().DeclaredMembers;
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static MemberInfo GetMember(this Type type, string name)
{
return type.GetTypeInfo().DeclaredMembers.First(x => x.Name == name);
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static bool IsreplacedignableTo<T>(this Type self)
{
return typeof(T).GetTypeInfo().IsreplacedignableFrom(self.GetTypeInfo());
}
19
Source : Utils.cs
with MIT License
from 71
with MIT License
from 71
internal static bool IsreplacedignableTo(this Type self, Type type)
{
return type.GetTypeInfo().IsreplacedignableFrom(self.GetTypeInfo());
}
19
Source : MacroExpander.cs
with MIT License
from 71
with MIT License
from 71
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
IInvocationExpression invocation = semanticModel.GetOperation(node, cancellationToken) as IInvocationExpression;
if (invocation == null)
return base.VisitInvocationExpression(node);
bool IsMacroMethod(ISymbol methodSymbol, out string error)
{
foreach (var attr in methodSymbol.GetAttributes())
{
if (attr.AttributeClreplaced.MetadataName != nameof(ExpandAttribute))
continue;
if (!methodSymbol.IsStatic)
error = "The target method must be static.";
else
error = null;
return true;
}
error = null;
return false;
}
// Check if it's a call to a macro method
var target = invocation.TargetMethod;
if (!IsMacroMethod(target, out string err))
return base.VisitInvocationExpression(node);
// Make sure it's valid
if (err != null)
throw new DiagnosticException($"Cannot call the specified method as a macro method: {err}.",
invocation.Syntax.GetLocation());
// It is a method, find it
MethodInfo method = target.GetCorrespondingMethod() as MethodInfo;
if (method == null)
throw new DiagnosticException("Cannot find corresponding method.", invocation.Syntax.GetLocation());
// Found it, make the arguments
ParameterInfo[] parameters = method.GetParameters();
object[] arguments = new object[parameters.Length];
for (int i = 0; i < arguments.Length; i++)
{
ParameterInfo param = parameters[i];
Type paramType = param.ParameterType;
if (param.HasDefaultValue)
arguments[i] = param.DefaultValue;
else
arguments[i] = paramType.GetTypeInfo().IsValueType
? Activator.CreateInstance(paramType)
: null;
}
// Set up the context
var statementSyntax = node.FirstAncestorOrSelf<StatementSyntax>();
var statementSymbol = new Lazy<IOperation>(() => semanticModel.GetOperation(statementSyntax, cancellationToken));
var callerSymbol = new Lazy<IMethodSymbol>(() => semanticModel.GetEnclosingSymbol(statementSyntax.SpanStart, cancellationToken) as IMethodSymbol);
var callerInfo = new Lazy<MethodInfo>(() => callerSymbol.Value?.GetCorrespondingMethod() as MethodInfo);
ExpressionSyntax expr;
StatementSyntax stmt;
using (CallBinder.EnterContext(invocation, statementSymbol, node, statementSyntax, method, target, callerInfo, callerSymbol))
{
// Invoke the method
try
{
method.Invoke(null, arguments);
}
catch (Exception e)
{
throw new DiagnosticException($"Exception thrown when expanding the '{method}' macro.", e, invocation.Syntax.GetLocation());
}
(expr, stmt) = CallBinder.Result;
}
// Edit the node accordingly
if (stmt != statementSyntax)
{
// Return the new statement
changes.Add(statementSyntax, stmt.WithTriviaFrom(statementSyntax).Accept(this) as StatementSyntax);
return node;
}
return base.Visit(expr == node ? expr : expr.WithTriviaFrom(node));
}
19
Source : Helpers.cs
with MIT License
from 71
with MIT License
from 71
public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
{
// First, try the good ol' RuntimeHelpers.PrepareMethod.
if (PrepareMethod != null)
{
PrepareMethod(handle);
return true;
}
// No chance, we gotta go lower.
// Invoke the method with uninitialized arguments.
object sender = null;
object[] GetArguments(ParameterInfo[] parameters)
{
object[] args = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
ParameterInfo param = parameters[i];
if (param.HasDefaultValue)
args[i] = param.DefaultValue;
else if (param.ParameterType.GetTypeInfo().IsValueType)
args[i] = Activator.CreateInstance(param.ParameterType);
else
args[i] = null;
}
return args;
}
if (!method.IsStatic)
{
// Gotta make the instance
Type declaringType = method.DeclaringType;
if (declaringType.GetTypeInfo().IsValueType)
{
sender = Activator.CreateInstance(declaringType);
}
else if (declaringType.GetTypeInfo().IsAbstract)
{
// Overkill solution: Find a type in the replacedembly that implements the declaring type,
// and use it instead.
throw new InvalidOperationException("Cannot manually JIT a method");
}
else if (GetUninitializedObject != null)
{
sender = GetUninitializedObject(declaringType);
}
else
{
/* TODO
* Since I just made the whole 'gotta JIT the method' step mandatory
* in the MethodRedirection ctor, i should make sure this always returns true.
* That means looking up every type for overriding types for the throwing step above,
* and testing every possible constructor to create the instance.
*
* Additionally, if we want to go even further, we can repeat this step for every
* single argument of the ctor, thus making sure that we end up having an actual clreplaced.
* In this case, unless the user wants to instantiate an abstract clreplaced with no overriding clreplaced,
* everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
* may mean scanning the replacedembly a dozen times for overriding types, calling their constructors
* hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
* perfs-friendly).
*/
ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);
if (ctor != null)
{
sender = ctor.Invoke(null);
}
else
{
ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);
Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));
ctor = ctors[0];
try
{
sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
}
catch (TargetInvocationException)
{
// Nothing we can do, give up.
return false;
}
}
}
}
try
{
method.Invoke(sender, GetArguments(method.GetParameters()));
}
catch (TargetInvocationException)
{
// That's okay.
}
return true;
}
19
Source : ReflectionExtensions.cs
with MIT License
from ababik
with MIT License
from ababik
public static ConstructorInfo[] GetInstanceConstructors(Type type)
{
return type
.GetTypeInfo()
.DeclaredConstructors
.Where(x => x.IsStatic == false)
.Where(x => x.IsPublic == true)
.ToArray();
}
19
Source : SortedObservableCollection`1.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
public int IndexOf(T item)
{
int index = this.list.BinarySearch(item, this.comparer);
if (index >= 0)
{
// The binary search found one sort-equivalent match, but it may not be the same object.
// Several similar objects may be sorted nearby.
// Make sure we find an exact match.
T foundItem = this[index];
bool isClreplaced = typeof(T).GetTypeInfo().IsClreplaced;
if (!Matches(foundItem))
{
// Look earlier in the list for an exact match.
for (int i = index - 1; i >= 0 && this.comparer.Compare(item, this[i]) == 0; i--)
{
if (Matches(this[i]))
{
return i;
}
}
// Look later in the list for an exact match.
for (int i = index + 1; i < this.Count; i++)
{
if (Matches(this[i]))
{
return i;
}
}
// No match.
return ~index;
}
bool Matches(T candidate) => isClreplaced ? ReferenceEquals(item, candidate) : EqualityComparer<T>.Default.Equals(item, candidate);
}
return index;
}
19
Source : ContextIsolatedTask.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
public sealed override bool Execute()
{
try
{
string taskreplacedemblyPath = new Uri(this.GetType().GetTypeInfo().replacedembly.CodeBase).LocalPath;
this.ctxt = new CustomreplacedemblyLoader(this);
replacedembly inContextreplacedembly = this.ctxt.LoadFromreplacedemblyPath(taskreplacedemblyPath);
Type innerTaskType = inContextreplacedembly.GetType(this.GetType().FullName);
object innerTask = Activator.CreateInstance(innerTaskType);
return this.ExecuteInnerTask(innerTask);
}
catch (OperationCanceledException)
{
this.Log.LogMessage(MessageImportance.High, "Canceled.");
return false;
}
}
19
Source : ContextIsolatedTask.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
private bool ExecuteInnerTask(object innerTask)
{
Type innerTaskType = innerTask.GetType();
Type innerTaskBaseType = innerTaskType;
while (innerTaskBaseType.FullName != typeof(ContextIsolatedTask).FullName)
{
innerTaskBaseType = innerTaskBaseType.GetTypeInfo().BaseType;
}
var outerProperties = this.GetType().GetRuntimeProperties().ToDictionary(i => i.Name);
var innerProperties = innerTaskType.GetRuntimeProperties().ToDictionary(i => i.Name);
var propertiesDiscovery = from outerProperty in outerProperties.Values
where outerProperty.SetMethod != null && outerProperty.GetMethod != null
let innerProperty = innerProperties[outerProperty.Name]
select new { outerProperty, innerProperty };
var propertiesMap = propertiesDiscovery.ToArray();
var outputPropertiesMap = propertiesMap.Where(pair => pair.outerProperty.GetCustomAttribute<OutputAttribute>() != null).ToArray();
foreach (var propertyPair in propertiesMap)
{
object outerPropertyValue = propertyPair.outerProperty.GetValue(this);
propertyPair.innerProperty.SetValue(innerTask, outerPropertyValue);
}
// Forward any cancellation requests
MethodInfo innerCancelMethod = innerTaskType.GetMethod(nameof(Cancel));
using (this.CancellationToken.Register(() => innerCancelMethod.Invoke(innerTask, new object[0])))
{
this.CancellationToken.ThrowIfCancellationRequested();
// Execute the inner task.
var executeInnerMethod = innerTaskType.GetMethod(nameof(ExecuteIsolated), BindingFlags.Instance | BindingFlags.NonPublic);
bool result = (bool)executeInnerMethod.Invoke(innerTask, new object[0]);
// Retrieve any output properties.
foreach (var propertyPair in outputPropertiesMap)
{
propertyPair.outerProperty.SetValue(this, propertyPair.innerProperty.GetValue(innerTask));
}
return result;
}
}
See More Examples