使用反射时,可以检查DynamicAttribute属性的字段,属性,索引器和参数,以确定它们是否具有动态类型。但是,这对于Methods不起作用 - 即使它们返回'dynamic',它们也没有属性,它们的返回类型是'object'(并且也没有属性)。 Visual Studio为intellisense为外部程序集中的方法执行此操作...可以使用反射来完成吗?
例如,下面的代码生成此输出:
dynamicField is dynamic DynamicProperty is dynamic Item is dynamic DynamicMethod is NOT dynamic!! dynamicParameter is dynamic
示例代码:
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace ReflectDynamics
{
class Program
{
static void Main()
{
var test = typeof(Test);
CheckDynamic(test.GetField("dynamicField"));
CheckDynamic(test.GetProperty("DynamicProperty"));
CheckDynamic(test.GetProperty("Item"));
MethodInfo dynamicMethod = test.GetMethod("DynamicMethod");
CheckDynamic(dynamicMethod);
CheckDynamic(dynamicMethod.GetParameters()[0]);
Console.ReadKey();
}
static void CheckDynamic(MemberInfo memberInfo)
{
bool isDynamic = memberInfo.GetCustomAttributes(typeof(DynamicAttribute), true).Length > 0;
Console.WriteLine(memberInfo.Name + (isDynamic ? " is dynamic" : " is NOT dynamic!!"));
}
static void CheckDynamic(ParameterInfo parameterInfo)
{
bool isDynamic = parameterInfo.GetCustomAttributes(typeof(DynamicAttribute), true).Length > 0;
Console.WriteLine(parameterInfo.Name + (isDynamic ? " is dynamic" : " is NOT dynamic!!"));
}
}
class Test
{
public dynamic dynamicField;
public dynamic DynamicProperty { get { return dynamicField; } }
public dynamic this[int index] { get { return dynamicField; } }
public dynamic DynamicMethod(dynamic dynamicParameter) { return dynamicField; }
}
}
答案 0 :(得分:4)
这是因为你需要从方法中检查ReturnTypeCustomAttributes
上的属性。
修改CheckDynamic
方法,如下所示:
static void CheckDynamic(MemberInfo memberInfo)
{
bool isDynamic = memberInfo.GetCustomAttributes(typeof(DynamicAttribute), true).Length > 0;
var methodInfo = (memberInfo as MethodInfo);
if (methodInfo != null)
{
isDynamic = methodInfo.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(DynamicAttribute), true).Length > 0;
}
Console.WriteLine(memberInfo.Name + (isDynamic ? " is dynamic" : " is NOT dynamic!!"));
}
这可能需要一些防御性编码,但它只是一个快速而肮脏的概念证明。