c# - 如何在不进行字符串比较的情况下获取类函数的 MethodInfo

标签 c# reflection fieldinfo memberinfo

类似于我之前的一个问题,当我询问获取字段的 FieldInfo 时,How to get the FieldInfo of a field from the value ,根据那里的答案,我编译了这个辅助类,

using System;
using System.Reflection;
using System.Linq.Expressions;

internal class Program
{
    class MyClass
    {
#pragma warning disable 0414, 0612, 0618, 0649
        private int myInt = 24;
#pragma warning restore 0414, 0612, 0618, 0649

        public const BindingFlags _flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

        public MyClass()
        {
            MemberInfo myIntMI = GetMemberInfo(this, c => c.myInt);
            Console.WriteLine(myIntMI.Name + ": " + GetFieldValue(myIntMI) + ", " + GetFieldInfo(myIntMI).FieldType);

//          MemberInfo tfMI = GetMemberInfo(this, cw => cw.testFunction());
//          MemberInfo tfMI = GetMemberInfo(this, cw => cw.testFunction);
//          Console.WriteLine(tfMI.Name + ": " + GetFieldValue(tfMI) + ", " + GetFieldInfo(tfMI).FieldType);

            foreach( var mi in GetType().GetMethods(_flags) )
            {
                Console.WriteLine("method: " + mi);
            }
        }

        private void testFunction() { }

        private object GetFieldValue(MemberInfo mi)
        {
            return GetFieldInfo(mi).GetValue(this);
        }

        private FieldInfo GetFieldInfo(MemberInfo mi)
        {
            return GetType().GetField(mi.Name, _flags);
        }

        private MemberInfo GetMemberInfo<TModel, TItem>(TModel model, Expression<Func<TModel, TItem>> expr)
        {
            return ( (MemberExpression)expr.Body ).Member;
        }
    }
}

使用 GetMemberInfo(this, c => c.myInt 效果非常好,但是注释掉的行是我现在很困惑的地方,GetMemberInfo(this, c = > c.testFunction)GetMemberInfo(this, c => c.testFunction())

有什么办法,不用字符串比较,我可以从 GetMethods() runthrough 或 GetMethod("testFunction") 中获取可用的成员信息?

最佳答案

MemberExpression仅适用于属性和字段。你可能会看MethodCallExpression .

有点像

((MethodCallExpression)expr.Body).Method

假设您传递了一个类似于 () => this.testFunction() 的 lambda

所以得到MemberInfo你会得到一个 Method MemberCallExpression 的属性.

此外,您应该更改 GetMemberInfo方法签名,因为这是一个不带参数并返回与您的方法返回相同类型的 lambda,所以它将是一个 private MemberInfo GetMemberInfo<T>(Expression<Func<T, void>> expr)或接近它的东西。

我不是 100% 确定,但实际情况是,this.testFunction实际上是委托(delegate)创建的语法糖,所以它实际上类似于 new Action(this.testFunction)假设 testFunctionvoid testFunction() .或者类似这样的东西,因为 this.testFunction不是成员访问,而是委托(delegate)创建。

关于c# - 如何在不进行字符串比较的情况下获取类函数的 MethodInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28986530/

相关文章:

c# - C# : What part defines the public key? 中的 RSA 加密

c# - 在Visual Studio 2008中设置/重置选项

reflection - 通过反射调用数据类copy()

c# - 如何在 Windows Phone 7 中的对象上设置结构类型的字段

.net - 如何通过反射引用字段

.net - BindingFlags 枚举中的 GetField、SetField、GetProperty 和 SetProperty 是什么?

c# - 在 Compact Framework 中使用 DLL VB6

c# - 具有使用 SSL 的上下文的 UserPrincipal

c# - 给定一个 C# 类型,获取它的基类和实现的接口(interface)

反射(reflection):检索属性值的不同方式