-1

我想修改下面的代码以便能够使用私有方法

        //use reflection to Load the data
    var method =
                    typeof(MemberDataFactory)
                    .GetMethod("LoadData")
                    .MakeGenericMethod(new [] { data.GetType() })
                    .Invoke(this, null);

我试过以下没有运气:

        //use reflection to Load the data
    var method =
                    typeof(MemberDataFactory)
                    .GetMethod("LoadData")
                    .MakeGenericMethod(new [] { data.GetType() })
                    .Invoke(this, BindingFlags.Instance | BindingFlags.NonPublic, null , null, null);

就这段代码而言,什么是“var”?我更喜欢指定它的类型而不是使用 var。

谢谢!

4

1 回答 1

3

你想使用这个重载Type.GetMethod()这是你传递绑定标志的地方。默认.GetMethod(string)只查找公共方法,因此它返回 null,因此您的 null 引用异常。

您的代码应该更像:

var method =
        typeof(MemberDataFactory)
        .GetMethod("LoadData", BindingFlags.Instance | BindingFlags.NonPublic) // binding flags go here
        ...
于 2012-09-01T17:55:17.427 回答