当前位置:网站首页>C regards type as generic type T and uses it as generic type of method
C regards type as generic type T and uses it as generic type of method
2022-07-26 12:51:00 【Roman Sultan Mohammed】
The problem is :
In general , It's impossible to Type Type as generic T To use the , You will receive IDE The tips are as follows 
Here, of course, you can directly Person Incoming generics , But I use one Person Class to get the Type Just for testing ,
because In some cases, we only have running Type object , I don't know its specific name .
And use it as a generic type of method
Press IDE A hint of , We can't use it directly like this ,
But Microsoft offers us The reflection method realizes this function
resolvent
Use 
public class Tests
{
public static string TestMethod<T>()
{
Console.WriteLine(" The specific incoming type is "+typeof(T));
return " It's a test ";
}
internal class Person
{
public string Name {
get; set; }
public int Id {
get; set; }
}
[Test]
public void Test1()
{
Type targetType = typeof(Person);
// Cannot be used directly
Tests.TestMethod<targetType>();
// have access to ,MakeGenericMethod You can get multiple one and more generics
MethodInfo method = typeof(Tests).GetMethod("TestMethod").MakeGenericMethod(targetType);
Console.WriteLine(method.Invoke(null, null));
}
[SetUp]
public void Setup()
{
}
}
}

Practical problems to solve :
I have one ASP.NET CORE Caching tools for ,
stay gitee You can check https://gitee.com/godenSpirit/cache-attribute
It uses SqlSugar Provided Redis Help class to implement the following interface
public interface ICacheable
{
/// <summary>
/// Generic get
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
T Get<T>(string key);
/// <summary>
/// object obtain
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
object Get(string key);
...........
}
When using non generic caching methods, you will get another layer of packaging object cache , Cannot return to Swagger
So use generic methods ,
The specific code is as follows ,
//[CacheAble Strategy ] Before the execution of the method , The first strategy is to comment on each line , If you look back, just refer to this
CacheAble_Strategy_Before = (context, _cache) => {
// Gets the Controller
ControllerActionDescriptor controller = (ControllerActionDescriptor)context.ActionDescriptor;
// Further obtain the reflection object of the called interface
MethodInfo method = controller.MethodInfo;
// Get the corresponding strategy from the reflection Attribute,
CacheAbleAttribute attribute = (CacheAbleAttribute)method.GetCustomAttribute(typeof(CacheAbleAttribute));
// obtain Attribute Cache name attribute that needs to be resolved in TotalName, analysis ToTalName, Replace to get the real cache name
string real_cacheName = CacheNameResolver.ResolveTotalName(attribute.Totoal_Name, context);
// If the parameter of the annotation is empty, an exception will be reported directly
if (string.IsNullOrEmpty(attribute.preffix) || string.IsNullOrEmpty(attribute.Totoal_Name))
throw new CacheAbleArgsException("The Args Cannot Be NULL");
// Get the resolved cache name and go to the cache to find whether there is the cache
if (_cache.Exist(attribute.preffix + real_cacheName)&&attribute.work==true)
{
//StandResult<object> res = _cache.Get<StandResult<object>>(attribute.preffix + real_cacheName); The return type of the flag used for the test , You can get
// Gets the type of the return value
Type returnType = method.ReturnType;
// Get generics Get Reflection of method ( By returning the value of Type Specify method generics )
MethodInfo GetGen = _cache.GetType().GetMethod("Get").MakeGenericMethod(returnType);
// Radiative call generics Get Method , Get the correct cache information
object res = GetGen.Invoke(_cache,new object[] {
attribute.preffix+real_cacheName});
return res;
}
else
{
return null; // Go back if you can't find it Null
}
};
For details, please check my CacheAttribute Source code of the tool , Comments are welcome .
边栏推荐
- Kubernetes----安装部署NFS服务器
- What is the Internet of things? The most comprehensive explanation of common IOT protocols
- 1-6月中国ADAS供应商占比9% 又一家零部件巨头全面布局智驾新赛道
- QT入门引导 及其 案例讲解
- Microsoft has shut down two attack methods: Office macro and RDP brute force cracking
- 数据查询函数
- C#把Type当做泛型T,来作为方法的泛型进行使用
- LCD笔记(5)LCD驱动程序框架_使用设备树
- 被罚“带薪休假”一个月后,谷歌解雇了“爱”上 AI 的他
- A super easy-to-use artifact apifox, throw swagger a few streets... (glory Collection Edition)
猜你喜欢

Some common writing methods and skills

Food safety | these common foods are poisonous! Check your dining table quickly

Microsoft has shut down two attack methods: Office macro and RDP brute force cracking

Various extensions of hcip-9.ospf

The map function counts the number of occurrences of characters

V00 - do whatever you want when you are old

食品安全 | 网购的自制食品就是健康食品?莫要陷入这些误区

STM32驱动HC05蓝牙串口通信模块

Huawei ultra fusion fusioncube solution notes

Ds-24c/dc220v time relay
随机推荐
高通再次「押宝」中科创达,挑战智能驾驶软硬件全栈方案
14.2字节流学习
Removable tablespace
历史上的今天:IBM 获得了第一项专利;Verizon 收购雅虎;亚马逊发布 Fire Phone...
JDBC gets connections from the connection pool (Druid connection pool)
Detailed explanation of redis's single login
Food safety | can you eat any fruit?
Industry case | how does the index help the sustainable development of Inclusive Finance in the banking industry
What is the Internet of things? The most comprehensive explanation of common IOT protocols
食品安全 | 微波炉什么食品都能加热?这些安全隐患要知道
回溯——131. 分割回文串
自定义浏览器默认右击菜单栏
HCIP-9.OSPF的各种拓展
Detailed explanation of redisson distributed lock process (II)
Code examples explain the difference between [reentrant lock] and [non reentrant lock]?
A super easy-to-use artifact apifox, throw swagger a few streets... (glory Collection Edition)
The programmed navigation route jumps to the current route (the parameters remain unchanged), and if it is executed multiple times, it will throw a navigationduplicated warning error?
一文看懂GaitSet中的test.py
About the copy of picture address links
笔记。。。。