在 C# 中对一个以 long 列表作为其唯一参数的方法陷入反射

问题描述 投票:0回答:1

我的

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”转换为“对象?[]?”

我该怎么办?

c# reflection
1个回答
0
投票

您正在调用

Type
的实例上的方法...您应该在
TeacherBusiness
的实例上调用它。 (所以 Invoke
first
参数是不正确的。)

不清楚为什么你首先通过反射来调用它,但你需要类似的东西:

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 });
© www.soinside.com 2019 - 2024. All rights reserved.