.net 反射,通过自定义Attribute动态调用类方法

自定义Attribute: 

public class ActiveAttribute : Attribute

    {

        public string Msg { get; set; }

        public ActiveAttribute(string msg)

        {

            Msg = msg;

        }

    }

自定义Attribute用于类:

namespace Test

{

    [ActiveAttribute("ActiveDemo1")]

    public class ActivityDemo : IActivity

    {

        public string View { set; get; }

        public dynamic GetData()

        {

            List<string> List1 = new List<string>();

            List1.Add("a");

            List1.Add("b");

            List<string> List2 = new List<string>();

            List2.Add("c");

            List2.Add("d");

            Dictionary<string, object> dic = new Dictionary<string, object>();

            dic.Add("key1", List1);

            dic.Add("key2", List2);

            return dic;

        }

    }

}


根据Attribute动态获取类:

 //assemblyName是dll名,attrStr是Attibute的msg

 public Type GetActivityClass(string assemblyName,string attrStr)

        {

            if (!String.IsNullOrEmpty(assemblyName))

            {

                assemblyName = path + assemblyName;

                try

                {

                    Assembly assembly = Assembly.LoadFrom(assemblyName);

                    Type[] ts = assembly.GetTypes();

                    foreach (Type t in ts)

                    {

                        var attrArr = t.GetCustomAttributes(typeof(ActiveAttribute), true);

                        ActiveAttribute attr = attrArr[0] as ActiveAttribute;

                        if (attr != null)

                        {

                            if (attr.Msg == attrStr)

                            {

                                return t;

                            }

                        }

                    }

                }

                catch (Exception e)

                {

                    Log4NetHelp.Log.Error(e.Message);

                    throw new Exception(e.Message);

                }

            }

            return null;

        }


获取类并调取其方法:

string assemblyName = "Test";

            Type t = assHelper.GetActivityClass(assemblyName, "ActiveDemo1");

            MethodInfo mInfo = t.GetMethod("GetData");

            object obj = Activator.CreateInstance(t);

            dynamic result = mInfo.Invoke(obj, null);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值