我一直在为标题中提到的概念而苦苦挣扎。我做了很多研究,找到了一些很好的例子,我尝试实施其中一些,但遇到了障碍。
我最初有一个看起来像这样的类:
namespace sysVer
{
public class testSuite
{
/* there is a bunch of test hardware setup
* and acquisition also that is not shown
*/
public struct testResultInfo
{
public testStatus testStat;
public bool warning, error;
public string warnStr, errStr, infoStr, muxDataStr;
public double measDecVal;
public Int16 measIntVal;
};
// NOTE there is no default constructor
public static testResultInfo testCase1()
{
}
public static testResultInfo testCase2()
{
}
public static testResultInfo testCase3()
{
}
// there are about 100 more
}
}
并使用带有 105 个复选框和字典的 Windows 窗体来确定用户想要运行的函数,我能够使用 Invoke Member 通过字符串调用函数,如下所示:
// first attempt
namespace sysVer
{
public partial class SysVerForm : Form
{
public static Pdgu1553ver.testResultInfo tcResult = new Pdgu1553ver.testResultInfo ( )
{
testStat = Pdgu1553ver.testStatus.pass,
warning = true,
error = true,
warnStr = "This is a warning",
errStr = "This is an error",
infoStr = "This is info",
muxDataStr = "Mux data of some sort",
measDecVal = 69.69,
measIntVal = 69
};
// for loop that iterates over checkbox checked items
foreach ( var checkedItem in checkedItems )
{
var funcName = "";
// retrieve function name from dictionary
tcToFuncDic.TryGetValue ( checkedItem.ToString ( ), out funcName );
tcResult = ( testSuite.testResultInfo ) typeof ( testSuite ).InvokeMember
(
funcName,
BindingFlags.InvokeMethod |
BindingFlags.Public |
BindingFlags.Static,
null,
null,
null
);
}
}
}
但是我在这里遇到了问题。当调用 InvokeMember 时,会执行静态方法并接收返回类型,但我不确定该方法是刚刚调用还是使用默认构造函数创建的类的实际实例?我开始注意到,在一次调用期间设置的此类的私有属性在另一次调用需要它们的不同静态函数期间不存在。
我假设我需要一个类的实例,所以我更改为以下内容:
namespace sysVer
{
public class testSuite
{
/* there is a bunch of test hardware setup
* and acquisition also that is not shown
*/
public struct testResultInfo
{
public testStatus testStat;
public bool warning, error;
public string warnStr, errStr, infoStr, muxDataStr;
public double measDecVal;
public Int16 measIntVal;
};
// constructor
public testSuite()
{
/* Here I initialize hardware, set variables, and
* run a few other tasks. All of which need to be done
* an exist before this object can be used
*/
}
public testResultInfo testCase1()
{
}
public testResultInfo testCase2()
{
}
public testResultInfo testCase3()
{
}
//... there are about 100 more
}
}
现在,我撞到了另一面墙。我需要做这样的事情:
testSuite myTest = new testSuite();
var blah = myTest.InvokeMember(
funcName,
BindingFlags.InvokeMethod |
BindingFlags.Public |
BindingFlags.Static,
null,
null,
null
);
但是我的课程不包含该方法。调查后我了解到我可以将我的类更改为从“Type”继承,并且我必须从“Type”中覆盖大约 50 个左右的抽象。我开始走这条路,但觉得这可能比我需要做的工作更多。
我需要有一个我的类的实例,并且需要能够在运行时推断出要调用哪个非静态方法。在我读过的许多帖子中,这两个: 如何通过反射调用非静态方法并在 c# 中调用非静态方法 似乎将我推向了正确的方向,但我仍然在某处遗漏了一些东西。
我已经花了很多时间来覆盖所有这些函数,但我被困在那里如何实际实现被覆盖的 InvokeMember 函数,我不想在此时撤消所有工作以尝试做其他事情。
一如既往,非常感谢任何建议。感谢您的时间和考虑。