C#通过字符串调用实例的非静态方法

如何解决C#通过字符串调用实例的非静态方法

我一直在努力解决标题中提到的概念。我做了大量研究,找到了一些很好的例子,我也尝试实施其中的一些,但遇到了障碍。

我最初有一个看起来像这样的类:

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 
                );
        }
    }
}

但是我在这里遇到了问题。当调用 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,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,null 
                );

但我的类不包含该方法。调查后,我了解到我可以将我的类更改为从“Type”继承,并且我必须覆盖大约 50 个来自“Type”的抽象。我开始走这条路,但觉得这可能比我在这里需要做的工作要多。

我需要有一个我的类的实例,并且需要能够在运行时推断出要调用的非静态方法。在我读过的许多帖子中,这两篇:How to invoke a non static method by reflectioninvoke non static method in c# 似乎把我推向了正确的方向,但我仍然在某处遗漏了一些东西。

我已经花了很多时间来覆盖所有这些函数,但是我一直在思考如何实际实现被覆盖的 InvokeMember 函数,我不想撤消所有这些工作来尝试在这一点上做其他事情。

一如既往,非常感谢任何建议。感谢您的时间和考虑。

解决方法

我感觉到您正在将大量假设和关注点与静态、结构、反射等混淆起来,并失去了您想去的地方。你显然试图以错误的方式解决错误的问题。但我会一次回答你一个问题。

我不确定该方法是刚刚调用还是使用默认构造函数创建的类的实际实例?

你为什么会这么想?您没有发布测试方法的代码,但我可以向您保证,InvokeMember 实际上调用了成员

我开始注意到在一次调用期间设置的此类的私有属性在另一次调用需要它们的不同静态函数时不存在。

可能是因为测试方法每次都会创建一个新的 testResultInfo,但是没有代码就不可能知道。但我不明白为什么这是一个问题。哪些数据需要“结转”?也许您需要 testResultInfo 上的静态 testSuite 属性可以在方法中重用?

调查后我了解到我可以更改我的类以从“类型”继承

我看不出有什么理由你需要这样做,或者你认为这会解决什么问题。

停止尝试因尝试修复其他问题而造成的顶级创可贴问题,可能是用错误的方式。备份、分析您的程序并考虑创建不同实例的位置?这些测试方法应该神奇地知道您在表单中创建的实例,还是应该以某种方式给予该实例?你应该怎么做?你应该把它作为输入参数吗?还是测试套件的静态属性?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res