【发布时间】:2021-03-02 09:36:11
【问题描述】:
(我想不出一个简洁的标题来解决这个问题。)
我有一个基类,它有一个公共方法:
public class MyBaseClass
{
public void MyBaseMethod()
{
// Here is where the functionality will go, that is described below.
}
}
我有另一个类,派生自我的基类,其中包含同样派生自 MyBaseClass 的注入对象:
public class MyWorkingClass : MyBaseClass
{
// All of these objects also derive from MyBaseClass.
private readonly IClassOne _classOne;
private readonly IClassTwo _classTwo;
private readonly IClassThree _classThree;
public MyWorkingClass(
IClassOne classOne,
IClassTwo classTwo,
IClassThree classThree)
{
_classOne = classOne;
_classTwo = classTwo;
_classThree = classThree;
}
public SomeMethod()
{
// Stuff goes here.
// Call base method here.
MyBaseMethod();
}
}
我想要发生的是对MyBaseMethod 的调用将收集类中声明的所有字段。对于每个字段,获取它的实例并调用它自己的MyBaseMethod。
我可以获取一个类实例中的所有字段:
var fields = GetType()
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.ToList();
对于列表中的每一个字段,我可以得到它的字段类型、实例以及它自己声明的方法:
foreach (var field in fields)
{
var fieldType = field.FieldType;
var fieldInstance = field
.GetValue(this);
var methods = fieldType
.GetMethods();
}
我的问题是我的基类方法MyBaseMethod 未包含在方法列表中。
我也试过GetRuntimeMethods(),但它也不包含在里面。
如果我可以访问基类方法,那么我可以调用它:
var methodInfo = fieldType
.GetMethod('MyBaseMethod');
methodInfo
.Invoke(fieldInstance, null);
问题:我如何设法在每个字段实例中调用我的基类方法,因为它的类型被列为接口?
谢谢。
【问题讨论】:
-
为什么您期望
MyBaseMethod在 IClassXxx 接口上可用,这非常令人困惑...一些edit 至少显示这些接口中的一个可能会有所帮助...您的推理为什么@ 987654333@ 应该出现在界面上也会有所帮助。
标签: c# reflection dependency-injection interface invoke