在使用反射时,可以检查字段、属性、索引器和参数的DynamicAttribute属性,以确定它们是否具有动态类型。然而,这并不适用于方法-即使他们返回"动态",他们没有属性,他们的返回类型是"对象"(也没有属性)。Visual Studio这样做是为了对外部程序集中的方法进行智能感知……这可以通过反思来完成吗?
例如,下面的代码产生如下输出: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; }
}
}
这是因为您需要从方法中检查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!!"));
}
这可能需要一些防御性的编码,但这只是一个快速和肮脏的概念证明。