遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

C#反射方式调用泛型方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace WindowsFormsApplication8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private  void  Paster<Ent>(String dicNo)
        where Ent : class, new()
        {
            var ent = new Ent();
            var list = new List<Ent>();
            for (int i = 0; i < 10; i++)
            {
                var e = new Ent();
                list.Add(e);
            }
            Console.WriteLine(typeof(Ent).ToString() + "__" + dicNo +"___" + ent);
            
        }
        private void button1_Click(object sender, EventArgs e)
        {



            Type t = this.GetType();
            BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
            var m1 = this.GetType().GetMethod("Paster", flags);
            var info= m1.MakeGenericMethod(typeof(SEnt));

             //object list = t.InvokeMember(null,
             //    BindingFlags.DeclaredOnly |
             //    BindingFlags.Public | BindingFlags.NonPublic |
             //    BindingFlags.Instance | BindingFlags.CreateInstance, null, null, new object[] { });


            info.Invoke(this,new Object[]{"ttt"});
     
        }
    }
    public class SEnt
    {
        public String Name { get; set; }
        public override string ToString()
        {
            return DateTime.Now.ToString();
        }
    }

}
View Code

 参考2:

using System;
using System.Reflection;

namespace RFTest
{
    //类ReflectionTest中定义了一个泛型函数DisplayType和泛型类MyGenericClass
    class ReflectionTest
    {
        //泛型类MyGenericClass有个静态函数DisplayNestedType
        public class MyGenericClass<T>
        {
            public static void DisplayNestedType()
            {
                Console.WriteLine(typeof(T).ToString());
            }
        }

        public void DisplayType<T>()
        {
            Console.WriteLine(typeof(T).ToString());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ReflectionTest rt = new ReflectionTest();

            MethodInfo mi = rt.GetType().GetMethod("DisplayType");//先获取到DisplayType<T>的MethodInfo反射对象
            mi.MakeGenericMethod(new Type[] { typeof(string) }).Invoke(rt, null);//然后使用MethodInfo反射对象调用ReflectionTest类的DisplayType<T>方法,这时要使用MethodInfo的MakeGenericMethod函数指定函数DisplayType<T>的泛型类型T

            Type myGenericClassType = rt.GetType().GetNestedType("MyGenericClass`1");//这里获取MyGenericClass<T>的Type对象,注意GetNestedType方法的参数要用MyGenericClass`1这种格式才能获得MyGenericClass<T>的Type对象
            myGenericClassType.MakeGenericType(new Type[] { typeof(float) }).GetMethod("DisplayNestedType", BindingFlags.Static | BindingFlags.Public).Invoke(null, null);
            //然后用Type对象的MakeGenericType函数为泛型类MyGenericClass<T>指定泛型T的类型,比如上面我们就用MakeGenericType函数将MyGenericClass<T>指定为了MyGenericClass<float>,然后继续用反射调用MyGenericClass<T>的DisplayNestedType静态方法

            Console.ReadLine();
        }
    }
}
View Code

参考3:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;
using System.ServiceModel;

namespace UI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CallContext.LogicalSetData("aa", "12343");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var t= CallContext.LogicalGetData("aa");
            Console.WriteLine(t);
        }

        private void button3_Click(object sender, EventArgs e)
        {

            var index= "23423".IndexOf("a");
            CallContext.FreeNamedDataSlot("aa");

            var methodName="TestA";
            var methodInfo= this.GetType().GetMethod(methodName);
            var ps= methodInfo.GetParameters();
            var attrs= methodInfo.GetCustomAttributes(typeof(OperationContractAttribute), false);
            if (attrs.Length > 0)
            {
                var attr = attrs[0] as OperationContractAttribute;
                var serviceTypeName = attr.Action;

                var serviceType = Type.GetType(serviceTypeName);
                var inType = ps[0].ParameterType;
                var outType = methodInfo.ReturnType;
                //var linkGenericType =typeof(LongInvokeLink<,,>);
                var linkGenericType = Type.GetType("UI.LongInvokeLink`3");
                var linkType=linkGenericType.MakeGenericType(inType, outType, serviceType);
                var service = Activator.CreateInstance(linkType, Guid.NewGuid().ToString());

                var completedMInfo = linkType.GetMethod("Complete4Success");
                var loadParamMInfo=linkType.GetMethod("Begin");
                var inModel=loadParamMInfo.Invoke(service,null);
                CallContext.SetData("Link", service);
                var outModel=methodInfo.Invoke(this,new object[]{inModel});
                CallContext.FreeNamedDataSlot("Link");
                completedMInfo.Invoke(service, new object[] { outModel });
                
            }
        }
        [OperationContract(Action = "UI.IService1")]
        public TestResponse TestA(TestRequest b)
        {
            var link = CallContext.GetData("Link") as ILongInvokeLink;
            link.P("搞点提示啊", 33);
            return new TestResponse() { Name = b + "aa" };
        }
    }
    public class Class12<T>
    {

    }
    public class TestRequest
    {
        public String Name { get; set; }
        public long Id { get; set; }
    }
    public class TestResponse
    {
        public String Name { get; set; }
        public long Id { get; set; }
    }

#region 
    public class LongInvokeLink<InType, OutType, ServiceType> : ILongInvokeLink
        where InType : class , new()
        where OutType : class
        where ServiceType :class
    {
        Object _Service;

        private String _Guid = null;
        public LongInvokeLink(string guid)
        {
            _Guid = guid;

        }
        public InType Begin()
        {
            return new InType();
        }
        public void Complete4Success(OutType model)
        {
            Console.WriteLine("Complete4Success");
        }
        public void P(string tips, int percent){

            Console.WriteLine(string.Format("tips:{0},percent{1}", tips, percent));
        }
        public void P(string tips)
        {
            P(tips, 50);
        
        }
        public void P(int percent)
        {
            P("222",60);
            
        }
    }

    public interface ILongInvokeLink
    {
        void P(string tips, int percent);

        void P(string tips);

        void P(int percent);
    }
#endregion
}
View Code

 参考4:

            #region 删除字表数据
            var dic4Call = new Dictionary<string, List<Type>>();
            dic4Call["menuCfg_"] = new List<Type>() { typeof(FF_FormMenuCfg), typeof(IFF_FormMenuCfgService) };
            dic4Call["statisticsCfg_"] = new List<Type>() { typeof(Sys_SQLStatistics), typeof(ISys_SQLStatisticsService)};
            dic4Call["importCfg_"] = new List<Type>() { typeof(FF_FormImportAct), typeof(IFF_FormImportActService)};
            dic4Call["authCfg_"] = new List<Type>() { typeof(FF_FormAuthorization), typeof(IFF_FormAuthorizationService)};
            dic4Call["fieldEditCfg_"] = new List<Type>() { typeof(FF_FormFieldEditCfg), typeof(IFF_FormFieldEditCfgService)};
            dic4Call["searchCfg_"] = new List<Type>() { typeof(FF_FormSearchCfg), typeof(IFF_FormSearchCfgService)};
            dic4Call["updateCfg_"] = new List<Type>() { typeof(FF_FormUpdateAct), typeof(IFF_FormUpdateActService)};
            dic4Call["fields_"] = new List<Type>() { typeof(FF_FormField), typeof(IFF_FormFieldService)};
            dic4Call["sfcCfg_"] = new List<Type>() { typeof(FF_FormSFCCfg), typeof(IFF_FormSFCCfgService) };
            dic4Call["moreMenuCfg_"] = new List<Type>() { typeof(FF_FormMoreMenuCfg), typeof(IFF_FormMoreMenuCfgService) };
            dic4Call["pkCfg_"] = new List<Type>() { typeof(FF_FormPKCfg), typeof(IFF_FormPKCfgService) };
            foreach (var item in dic4Call.Values)
            {
                

                var field = item[0].Name == "Sys_SQLStatistics" ? "SQLNo" : "FormNo";
                var delSQL = string.Format("delete from {0} Where {1}='{2}'", item[0].Name,field,freeForm.FormNo );

                #region 注意代理类的反射创建与接口方法反射是分开的
                var method = typeof(ServiceLocator).GetMethod("Fetch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                var fetchMethod = method.MakeGenericMethod((Type)item[1]);
                var srv = fetchMethod.Invoke(this, null);
                var method2 = item[1].GetInterface("IDaoBase`1").GetMethod("ExeSql");//非常操蛋--要先获取父接口
                method2.Invoke(srv, new object[] { delSQL });
                #endregion
                //Fetch<IFF_FormService>().ExeSql(delSQL);
                //Console.WriteLine(delSQL);
                
            }
            #endregion
View Code

 参考:

            var type4Card = typeof(ZJ_Task_Card);
            foreach (var it in _ProcHandleCfgList)
            {
                it.ParamListProperty = type4Card.GetProperty(it.ParamListPropertyName);
                //等价于ParamEntType = typeof(YT_Task_Card_Param)
                it.ParamListEntType = it.ParamListProperty.PropertyType.GetGenericArguments()[0];
            }
View Code

 

                var hCfg = _ProcHandleCfgList.FirstOrDefault(ent => ent.ProcNo == card.PAType);
                if (hCfg == null) throw new Exception(string.Format("工序{0}未配置工序处理信息!",card.PAType));
                var pty = hCfg.ParamListProperty;
                var paramList = pty.GetValue(card, null) as IList;
                if (!paramListDic.ContainsKey(pty))
                {
                    var paramType = hCfg.ParamListEntType;
                    var listType = typeof(List<>).MakeGenericType(paramType);
                    paramListDic[pty] = Activator.CreateInstance(listType) as IList;
                }
                foreach (var param in paramList)
                {
                    paramListDic[pty].Add(param);

                }

                #region
                var type = paramList.GetType().GetGenericArguments()[0];
                var serviceTypeName = string.Format("com.geelyhd.MFG.IService.I{0}Service", type.Name);
                var serviceType = Assembly.Load("com.geelyhd.MFG.IService").GetType(serviceTypeName);

                var method = typeof(ServiceLocator).GetMethod("Fetch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                var fetchMethod = method.MakeGenericMethod(serviceType);
                var srv = fetchMethod.Invoke(this, null);
                var method2 = serviceType.GetInterface("IDaoBase`1").GetMethod("AddList");//非常操蛋--要先获取父接口
                // method2.Invoke(srv, new object[] { delSQL });

                #endregion
View Code

 

posted on 2019-12-06 09:12  遗忘海岸  阅读(2494)  评论(0编辑  收藏  举报