C# 根据类的名称string,传参,执行该类下的方法(高端操作)

我有一个类

    class ExportData
    {
        [Export("TextInfo")]
        public string ExportInfo(Document document)
        {
           
            return "这是返回的字符串";
        }
        [Export("TextInfo2")]
        public string ExportInfo2(Document document,int a)
        {
           
            return "这还是返回的字符串";
        }
    }

我要通过代码,去创建上面那个类对象,把该类里边所有方法执行一遍,并获取到 每个方法返回的字符串和 Export 中的字符串信息,方法入下

        private void ExportData(Type type)
        {
            //导出道路信息及指标
            Dictionary<string, string> resultDic = new Dictionary<string, string>();
            object roadObj = Activator.CreateInstance(type);//实例化
            foreach (MethodInfo m in type.GetMethods())
            {
                foreach (Attribute a in m.GetCustomAttributes(true))
                {
                    ExportAttribute ea = a as ExportAttribute;
                    if (null != ea)
                    {
                        if (m.Name == "TextInfo2")//这个方法需要传入3个参数
                        {
                            resultDic.Add(ea.Key, (string)m.Invoke(roadObj, new object[] { RevitDoc, 3 }));
                        }
                        else
                        {
                            resultDic.Add(ea.Key, (string)m.Invoke(roadObj, new object[] { RevitDoc }));
                        }

                    }
                }
            }
            //最终得到 resultDic ,即为 export 字符串 和 方法返回的字符串的字典集合
        }

 

奥还需要用到这个类

    [AttributeUsage(AttributeTargets.Method)]
    class ExportAttribute : System.Attribute
    {
        private string key;

        public string Key { get => key; set => key = value; }

        public ExportAttribute(string key)
        {
            this.Key = key;
        }
    }

最后,调用方法执行即可

 ExportData(typeof(ExportData));

公司大神写的,仅记录。

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GIS程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值