小编Ian*_*Ian的帖子

.NET 2.0:使用反射和泛型调用方法会导致异常

我是Stack Overflow的新手,请原谅我.我刚开始转移到C#,我遇到了问题.

我想传递一个泛型类并从该类调用一个方法.所以,我的代码看起来像这样:

public void UpdateRecords<T>(T sender) where T : new() //where T: new() came from Resharper
{
    Type foo = Type.GetType(sender.GetType().ToString());
    object[] userParameters = new object[2];
    userParameters[0] = x;
    userParameters[1] = y;
    sender = new T(); //This was to see if I could solve my exception problem
    MethodInfo populateRecord = foo.GetMethod("MethodInOtherClass");
    populateMethod.Invoke(sender, userParameters);
}
Run Code Online (Sandbox Code Playgroud)

抛出异常:"对象引用未设置为对象的实例."

我再次道歉,因为我几乎是C#的新手,这是我第一次处理反射和泛型.谢谢!

.net c# generics reflection .net-2.0

2
推荐指数
1
解决办法
743
查看次数

标签 统计

.net ×1

.net-2.0 ×1

c# ×1

generics ×1

reflection ×1