在 C# 中,对于将 long 列表作为其唯一参数的方法,卡在反射处

Stuck at reflection in C# for a method with a list of long as its only parameter

提问人:behnam rahmani 提问时间:11/15/2023 更新时间:11/15/2023 访问量:59

问:

我的班级里有这个方法:TeacherBusiness.cs

public List<Teacher> GetList(List<long> ids)

我想通过反思来称呼它。这是我所做的:

var ids = new List<long> { 1, 2, 3 }
var business = typeof(TeacherBusiness);
var getListMethod = business.GetMethod("GetList", new System.Type[] { typeof(List<long>) });
var entities = getListMethod.Invoke(business, new object[] { ids });

但是,当我调用它时,出现此错误:

对象与目标类型不匹配。

我被困在这一点上。

如果我将调用代码更改为代码将无法编译,并且出现此错误:getListMethod.Invoke(business, ids)

错误 CS1503:参数 2:无法从“System.Collections.Generic.List”转换为“object?[]?'

我该怎么办?

C# 反射

评论

1赞 Dmitry Bychenko 11/15/2023
您应该传递实例,而不是键入 into : 然后businessgetListMethod.Invoke(businessTeacherBusiness someBusiness = new TeacherBusiness();getListMethod.Invoke(someBusiness, ...);

答:

6赞 Jon Skeet 11/15/2023 #1

您正在调用在 ...您应该在 的实例上调用它。(所以这是第一个不正确的论点。TypeTeacherBusinessInvoke

目前还不清楚为什么你首先通过反射来调用它,但你需要这样的东西:

var ids = new List<long> { 1, 2, 3 }
var businessType = typeof(TeacherBusiness);
var businessInstance = new TeacherBusiness(); // Or however you get that...
var getListMethod = businessType.GetMethod("GetList", new[]{ typeof(List<long>) });
var entities = getListMethod.Invoke(businessInstance, new object[] { ids });