Obtenha um tipo genérico de chamada para método em objeto dinâmico
-
14-11-2019 - |
Pergunta
Estou começando a trabalhar com objetos dinâmicos em .Net e não consigo descobrir como fazer algo.
Eu tenho uma classe que herda de DynamicObject e substituo o método TryInvokeMember.
por exemplo.
class MyCustomDynamicClass : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
// I want to know here the type of the generic argument
}
}
E dentro desse método quero saber o tipo (se houver) dos argumentos genéricos na invocação.
por exemplo.Se eu invocar o código a seguir, desejo obter o valor de System.Boolean e System.Int32 dentro do método substituído do meu objeto dinâmico
dynamic myObject = new MyCustomDynamicClass();
myObject.SomeMethod<bool>("arg");
myObject.SomeOtherMethod<int>("arg");
Atualmente, se eu colocar um ponto de interrupção dentro do método substituído, posso obter o nome do método que está sendo invocado ("SomeMethod" e "SomeOtherMethod", e também os valores dos argumentos, mas não os tipos genéricos).
Como posso obter esses valores?
Obrigado!
Solução
Na verdade olhei na hierarquia do fichário e encontrei uma propriedade com os valores necessários nos campos internos do objeto.
O problema é que a propriedade não é exposta porque usa classes/códigos específicos do C#, portanto as propriedades devem ser acessadas usando Reflection.
Encontrei o código neste blog japonês: http://neue.cc/category/programming (Eu não leio nenhum japonês, portanto não tenho certeza se o autor realmente descreve o mesmo problema
Aqui está o trecho:
var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder");
var typeArgs = (csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList<Type>);
typeArgs é uma lista que contém os tipos de argumentos genéricos usados ao invocar o método.
Espero que isso ajude outra pessoa.
Outras dicas
Pesquisando um pouco no Google e tenho uma solução bastante genérica para .NET e Mono:
/// <summary>Framework detection and specific implementations.</summary>
public static class FrameworkTools
{
private static bool _isMono = Type.GetType("Mono.Runtime") != null;
private static Func<InvokeMemberBinder, IList<Type>> _frameworkTypeArgumentsGetter = null;
/// <summary>Gets a value indicating whether application is running under mono runtime.</summary>
public static bool IsMono { get { return _isMono; } }
static FrameworkTools()
{
_frameworkTypeArgumentsGetter = CreateTypeArgumentsGetter();
}
private static Func<InvokeMemberBinder, IList<Type>> CreateTypeArgumentsGetter()
{
if (IsMono)
{
var binderType = typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.GetType("Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder");
if (binderType != null)
{
ParameterExpression param = Expression.Parameter(typeof(InvokeMemberBinder), "o");
return Expression.Lambda<Func<InvokeMemberBinder, IList<Type>>>(
Expression.TypeAs(
Expression.Field(
Expression.TypeAs(param, binderType), "typeArguments"),
typeof(IList<Type>)), param).Compile();
}
}
else
{
var inter = typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.GetType("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder");
if (inter != null)
{
var prop = inter.GetProperty("TypeArguments");
if (!prop.CanRead)
return null;
var objParm = Expression.Parameter(typeof(InvokeMemberBinder), "o");
return Expression.Lambda<Func<InvokeMemberBinder, IList<Type>>>(
Expression.TypeAs(
Expression.Property(
Expression.TypeAs(objParm, inter),
prop.Name),
typeof(IList<Type>)), objParm).Compile();
}
}
return null;
}
/// <summary>Extension method allowing to easyly extract generic type arguments from <see cref="InvokeMemberBinder"/>.</summary>
/// <param name="binder">Binder from which get type arguments.</param>
/// <returns>List of types passed as generic parameters.</returns>
public static IList<Type> GetGenericTypeArguments(this InvokeMemberBinder binder)
{
// First try to use delegate if exist
if (_frameworkTypeArgumentsGetter != null)
return _frameworkTypeArgumentsGetter(binder);
if (_isMono)
{
// In mono this is trivial.
// First we get field info.
var field = binder.GetType().GetField("typeArguments", BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
// If this was a success get and return it's value
if (field != null)
return field.GetValue(binder) as IList<Type>;
}
else
{
// In this case, we need more aerobic :D
// First, get the interface
var inter = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder");
if (inter != null)
{
// Now get property.
var prop = inter.GetProperty("TypeArguments");
// If we have a property, return it's value
if (prop != null)
return prop.GetValue(binder, null) as IList<Type>;
}
}
// Sadly return null if failed.
return null;
}
}
Divirta-se.Aliás, o Impromptu é legal, mas não consigo usar.
A estrutura de código aberto Dinamite pode chamar propriedades internas/protegidas/privadas usando o DLR e, portanto, funciona com o Silverlight.Mas fica um pouco complicado com membros explícitos da interface, pois você precisa usar o nome completo real do membro no tipo, em vez do nome do membro da interface.Então você pode fazer:
var typeArgs = Dynamic.InvokeGet(binder, "Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder.TypeArguments")
as IList<Type>;