我的
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”转换为“对象?[]?”
我该怎么办?
您正在调用
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 });