我无法在C#7.0中通过反射从valuetuple获取参数名称

编程入门 行业动态 更新时间:2024-10-28 18:33:25
本文介绍了我无法在C#7.0中通过反射从valuetuple获取参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用反射将ValueTuple映射到一个类。 文档说ValueTuple附加了一个带有参数名称的属性(Item1,Item2等除外),但我看不到任何属性。

反汇编什么都没有显示。

会发生什么事?

示例:

公共静态T ToStruct< T,T1,T2>(此ValueTuple< T1,T2>元组)其中T:结构

通过反射无法通过反射使Item1,Item2名称与T字段匹配。

解决方案

您应在编译器创建的方法上具有 TupleElementNames 属性。

请参见 m pre> public class C { public(int a,int b)M(){ return(1,2); } }

编译为:

[返回:TupleElementNames(新字符串[] { a, b })] public ValueTuple< int,int> M() {返回新的ValueTuple< int,int>(1,2); }

您可以使用以下代码获取该属性:

Type t = typeof(C); MethodInfo方法= t.GetMethod(nameof(C.M)); var attr = method.ReturnParameter.GetCustomAttribute< TupleElementNamesAttribute>(); string []名称= attr.TransformNames;

I want to Map a ValueTuple to a class using reflection. Documentation says that there is a Attribute attached to ValueTuple with parameters names (others than Item1, Item2, etc...) but I can't see any Attribute.

Disassembly shows nothing.

What's happens?

Example:

public static T ToStruct<T, T1,T2>(this ValueTuple<T1,T2> tuple) where T : struct

Via reflection can't get Item1, Item2 names to match with T fields via reflection.

解决方案

You should have the TupleElementNames attribute on the method created by the compiler.

See this code:

public class C { public (int a, int b) M() { return (1, 2); } }

Which compiles to:

[return: TupleElementNames(new string[] { "a", "b" })] public ValueTuple<int, int> M() { return new ValueTuple<int, int>(1, 2); }

You can get that attribute using this code:

Type t = typeof(C); MethodInfo method = t.GetMethod(nameof(C.M)); var attr = method.ReturnParameter.GetCustomAttribute<TupleElementNamesAttribute>(); string[] names = attr.TransformNames;

更多推荐

我无法在C#7.0中通过反射从valuetuple获取参数名称

本文发布于:2023-11-04 10:41:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557699.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   名称   参数   valuetuple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!