我想使用反射将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 : structVia 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获取参数名称
发布评论