net core 反射获取泛型-泛型方法method<T>(T t1)

参考微软说明: How to: Examine and Instantiate Generic Types with Reflection - .NET Framework | Microsoft Learn

目标方法

    public class GenericTest{public Dictionary<string, string> TestGeneric<T1, T2>(T1 t1, T2 t2)where T1 : TestBase, ITestArgument where T2 : class, new(){return null;}}

//判断逻辑

var testType = typeof(GenericTest);
var methods = testType.GetMethods();//获取泛型方法
var genericMethod = methods[0];
//判断是否是泛型
if (!genericMethod.IsGenericMethod)
{return;
}
//获取泛型信息<T1, T2>
var genericArgs = genericMethod.GetGenericArguments();
//获取泛型T1
var arg1 = genericArgs[0];
//获取T1名称
var name = arg1.Name;
//获取约束 T1约束, where T1: TestBase, ITestArgument
var arg1constraints = arg1.GetGenericParameterConstraints();
foreach (Type iConstraint in arg1constraints)
{if (iConstraint.IsInterface){//ITestArgumentvar itestArgumentName = iConstraint.Name;}else{//TestBasevar testBaseName = iConstraint.Name;}
}
//获取T2约束 where T2 : class, new()
var arg2 = genericArgs[1];
GenericParameterAttributes arg2Constraints =arg2.GenericParameterAttributes &GenericParameterAttributes.SpecialConstraintMask;if (arg2Constraints != GenericParameterAttributes.None)
{if (GenericParameterAttributes.None != (arg2Constraints &GenericParameterAttributes.DefaultConstructorConstraint)){//包含 new()}if (GenericParameterAttributes.None != (arg2Constraints &GenericParameterAttributes.ReferenceTypeConstraint)){//包含 class}if (GenericParameterAttributes.None != (arg2Constraints &GenericParameterAttributes.NotNullableValueTypeConstraint)){//包含 notnull}
}

官网示例代码

using System;
using System.Reflection;
using System.Collections.Generic;// Define an example interface.
public interface ITestArgument {}// Define an example base class.
public class TestBase {}// Define a generic class with one parameter. The parameter
// has three constraints: It must inherit TestBase, it must
// implement ITestArgument, and it must have a parameterless
// constructor.
public class Test<T> where T : TestBase, ITestArgument, new() {}// Define a class that meets the constraints on the type
// parameter of class Test.
public class TestArgument : TestBase, ITestArgument
{public TestArgument() {}
}public class Example
{// The following method displays information about a generic// type.private static void DisplayGenericType(Type t){Console.WriteLine("\r\n {0}", t);Console.WriteLine("   Is this a generic type? {0}",t.IsGenericType);Console.WriteLine("   Is this a generic type definition? {0}",t.IsGenericTypeDefinition);// Get the generic type parameters or type arguments.Type[] typeParameters = t.GetGenericArguments();Console.WriteLine("   List {0} type arguments:",typeParameters.Length);foreach( Type tParam in typeParameters ){if (tParam.IsGenericParameter){DisplayGenericParameter(tParam);}else{Console.WriteLine("      Type argument: {0}",tParam);}}}// The following method displays information about a generic// type parameter. Generic type parameters are represented by// instances of System.Type, just like ordinary types.private static void DisplayGenericParameter(Type tp){Console.WriteLine("      Type parameter: {0} position {1}",tp.Name, tp.GenericParameterPosition);Type classConstraint = null;foreach(Type iConstraint in tp.GetGenericParameterConstraints()){if (iConstraint.IsInterface){Console.WriteLine("         Interface constraint: {0}",iConstraint);}}if (classConstraint != null){Console.WriteLine("         Base type constraint: {0}",tp.BaseType);}else{Console.WriteLine("         Base type constraint: None");}GenericParameterAttributes sConstraints =tp.GenericParameterAttributes &GenericParameterAttributes.SpecialConstraintMask;if (sConstraints == GenericParameterAttributes.None){Console.WriteLine("         No special constraints.");}else{if (GenericParameterAttributes.None != (sConstraints &GenericParameterAttributes.DefaultConstructorConstraint)){Console.WriteLine("         Must have a parameterless constructor.");}if (GenericParameterAttributes.None != (sConstraints &GenericParameterAttributes.ReferenceTypeConstraint)){Console.WriteLine("         Must be a reference type.");}if (GenericParameterAttributes.None != (sConstraints &GenericParameterAttributes.NotNullableValueTypeConstraint)){Console.WriteLine("         Must be a non-nullable value type.");}}}public static void Main(){// Two ways to get a Type object that represents the generic// type definition of the Dictionary class.//// Use the typeof operator to create the generic type// definition directly. To specify the generic type definition,// omit the type arguments but retain the comma that separates// them.Type d1 = typeof(Dictionary<,>);// You can also obtain the generic type definition from a// constructed class. In this case, the constructed class// is a dictionary of Example objects, with String keys.Dictionary<string, Example> d2 = new Dictionary<string, Example>();// Get a Type object that represents the constructed type,// and from that get the generic type definition. The// variables d1 and d4 contain the same type.Type d3 = d2.GetType();Type d4 = d3.GetGenericTypeDefinition();// Display information for the generic type definition, and// for the constructed type Dictionary<String, Example>.DisplayGenericType(d1);DisplayGenericType(d2.GetType());// Construct an array of type arguments to substitute for// the type parameters of the generic Dictionary class.// The array must contain the correct number of types, in// the same order that they appear in the type parameter// list of Dictionary. The key (first type parameter)// is of type string, and the type to be contained in the// dictionary is Example.Type[] typeArgs = {typeof(string), typeof(Example)};// Construct the type Dictionary<String, Example>.Type constructed = d1.MakeGenericType(typeArgs);DisplayGenericType(constructed);object o = Activator.CreateInstance(constructed);Console.WriteLine("\r\nCompare types obtained by different methods:");Console.WriteLine("   Are the constructed types equal? {0}",(d2.GetType()==constructed));Console.WriteLine("   Are the generic definitions equal? {0}",(d1==constructed.GetGenericTypeDefinition()));// Demonstrate the DisplayGenericType and// DisplayGenericParameter methods with the Test class// defined above. This shows base, interface, and special// constraints.DisplayGenericType(typeof(Test<>));}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/98925.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Windows11 安全中心页面不可用问题(无法打开病毒和威胁防护)解决方案汇总(图文介绍版)

本文目录 Windows版本与报错信息问题详细图片&#xff1a; 解决方案:方案一、管理员权限&#xff08;若你确定你的电脑只有你一个账户&#xff0c;则此教程无效&#xff0c;若你也不清楚&#xff0c;请阅读后再做打算&#xff09;方案二、修改注册表(常用方案)方案三、进入开发…

leetcode:2427. 公因子的数目(python3解法)

难度&#xff1a;简单 给你两个正整数 a 和 b &#xff0c;返回 a 和 b 的 公 因子的数目。 如果 x 可以同时整除 a 和 b &#xff0c;则认为 x 是 a 和 b 的一个 公因子 。 示例 1&#xff1a; 输入&#xff1a;a 12, b 6 输出&#xff1a;4 解释&#xff1a;12 和 6 的公因…

Meta分析的流程及方法

Meta分析是针对某一科研问题&#xff0c;根据明确的搜索策略、选择筛选文献标准、采用严格的评价方法&#xff0c;对来源不同的研究成果进行收集、合并及定量统计分析的方法&#xff0c;最早出现于“循证医学”&#xff0c;现已广泛应用于农林生态&#xff0c;资源环境等方面。…

linux日志审计常用命令

文章目录 cut参数指定范围命令 awk参数内置变量命令 wc参数命令 uniq参数命令 sort参数命令 head参数 cut 参数 选项含义-b仅显示行中指定直接范围的内容-c仅显示行中指定范围的字符-d指定分割符&#xff0c; 默认为“TAB”制表符-f显示指定字段的内容-n与“-b”连用&#xf…

Prometheus普罗米修斯

什么是Prometheus 官网&#xff1a;Overview | Prometheus 是一个开源的系统监控和警报工具&#xff0c;多数Prometheus组件是Go语言写的 为用户提供可视化仪表板、警报、告警等功能&#xff0c;以帮助用户快速定位和解决问题 现在已经成为一个独立于企业级的开源项目和一个…

供水管网监测系统

随着城市人口的不断增长和经济的快速发展&#xff0c;供水管网的安全和可靠性变得尤为重要。在过去&#xff0c;供水管网的监测往往是依靠人工巡查&#xff0c;这种方式不仅费时费力&#xff0c;而且容易出现疏漏和盲区。然而&#xff0c;随着科技的进步&#xff0c;供水管网监…

大数据集群(Hadoop生态)安装部署

目录 1. 简介 2. 前置要求 3. Hadoop集群角色 4. 角色和节点分配 5. 调整虚拟机内存 6. Zookeeper集群部署 7. Hadoop集群部署 7.1 下载Hadoop安装包、解压、配置软链接 7.2 修改配置文件&#xff1a;hadoop-env.sh 7.3 修改配置文件&#xff1a;core-site…

Vue3目录结构与Yarn.lock 的版本锁定

Vue目录结构与Yarn.lock 的版本锁定 一、Vue3.0目录结构图总览 举个例子看vue的目录&#xff0c;一开始不知道该目录是什么意思目录里各个文件包里安放有什么&#xff0c;程序员在哪里操作该如何操作。 下图目录看Vue新项目 VS Code 打开文件包后出现一列目录 二、目录结构 1…

宝塔面板二次元透明主题美化模板

看惯了宝塔面板默认风格模板&#xff0c;我们可以试试自己美化修改&#xff0c;我的站长站知道一款非常漂亮的宝塔面板二次元透明主题美化模板&#xff0c;美不美大家看下图&#xff0c;分享给大家。 下载&#xff1a;飞猫盘&#xff5c;文件加速传输工具&#xff5c;云盘&…

怎么使用jenkins设置web自动打包

在Jenkins中设置Web自动打包需要完成以下步骤&#xff1a; 1.环境基础 安装Jenkins&#xff1a;首先&#xff0c;你需要在服务器上安装Jenkins。 你可以从Jenkins官网下载Jenkins的安装包&#xff0c;并按照官方指导进行安装。 2.使用jenkins设置web自动打包步骤 创建Jenk…

Vulnhub系列靶机-The Planets Earth

文章目录 Vulnhub系列靶机-The Planets: Earth1. 信息收集1.1 主机扫描1.2 端口扫描1.3 目录爆破 2. 漏洞探测2.1 XOR解密2.2 解码 3. 漏洞利用3.1 反弹Shell 4. 权限提升4.1 NC文件传输 Netcat&#xff08;nc&#xff09;文件传输 Vulnhub系列靶机-The Planets: Earth 1. 信息…

Hadoop2复安装过程详细步骤

1、在vmware中更改了虚拟机的网络类型&#xff0c;--->NAT方式&#xff0c;&#xff08;虚拟交换机的ip可以从vmvare的edit-->vertual network editor看到&#xff09; 2、根据这个交换机&#xff08;网关&#xff09;的地址&#xff0c;来设置我们的客户端windows7的ip&…

软件工程师都应该知道的10个定律

一、海勒姆法则 内容 当一个 API 有足够多的用户&#xff0c;你在契约中承诺了什么并不重要&#xff1a;系统中所有看得见的行为都会有某个人依赖…… 案例 现在有两个系统A和B&#xff0c;B的一个接口返回一个列表。A系统的开发人员发现返回的列表都是按照ID正向排序的。本…

vue-组件定义注册使用

vue组件使用的步骤 定义组件注册组件使用组件 定义组件 Vue.extend(options) 其中options和new Vue(options)出入的options对象几乎一样&#xff0c;但是也有不同。 创建 el不用写—最终所有组件需要经过一个vm的管理&#xff0c;由vm的el决定服务哪个容器。 data必须写成函…

Flink实现kafka到kafka、kafka到doris的精准一次消费

1 流程图 2 Flink来源表建模 --来源-城市topic CREATE TABLE NJ_QL_JC_SSJC_SOURCE ( record string ) WITH (connector = kafka,topic = QL_JC_SSJC,properties.bootstrap.servers = 172.*.*.*:9092,properties.group.id = QL_JC_SSJC_NJ_QL_JC_SSJC_SOURCE,scan.startup.mo…

基于Springboot实现疫情网课管理系统项目【项目源码+论文说明】分享

基于Springboot实现疫情网课管理系统演示 摘要 随着科学技术的飞速发展&#xff0c;各行各业都在努力与现代先进技术接轨&#xff0c;通过科技手段提高自身的优势&#xff1b;对于疫情网课管理系统当然也不能排除在外&#xff0c;随着网络技术的不断成熟&#xff0c;带动了疫情…

学习开发一个RISC-V上的操作系统(汪辰老师) — unrecognized opcode `csrr t0,mhartid‘报错问题

前言 &#xff08;1&#xff09;此系列文章是跟着汪辰老师的RISC-V课程所记录的学习笔记。 &#xff08;2&#xff09;该课程相关代码gitee链接&#xff1b; &#xff08;3&#xff09;PLCT实验室实习生长期招聘&#xff1a;招聘信息链接 正文 &#xff08;1&#xff09;在跟着…

three.js点击模型实现模型边缘高亮选中效果

three.jsreact实现点击模型实现高亮选中效果 1、创建一个场景 let scene, camera, renderer, controls; let stats null; // 检测动画运行时的帧数 let clock new THREE.Clock(); // getDelta()方法获得两帧的时间间隔 let FPS 30; let renderT 1 / FPS; let timeS 0;con…

SpringBoot中使用拦截器

拦截器属于MVC中的内容 SpringBoot项目,引入web依赖即可 需要访问的控制器 拦截器第一步实现HandlerInterceptor接口 第二步实现WebMvcConfigurer接口,并重写addInterCeptors()方法,将自定义的拦截器注册 也就是说这里add进去拦截的请求,才会进入到prehandle方法,这里放行的请…

kafka与zookeeper的集群

基础配置 systemctl stop firewalld && systemctl disable firewalld setenforce 0 sed -i s/SELINUXenforcing/SELINUXdisabled/ /etc/selinux/configvi /etc/hosts ip1 node1 ip2 node2 ip3 node3zookeeper介绍 zookeeper是一个分布式的协调服务&#xff0c;主要用…