I cannot get parameter names from valuetuple through reflection in C # 7.0

I want to map a ValueTuple to a class using reflection. The documentation says that there is an attribute attached to the ValueTuple with parameter names (other than Item1, Item2, etc.), but I do not see any attribute.

Dismantling does not show anything.

What's happening?

Example:

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

It is impossible to get the names Item1, Item2 through reflection in accordance with the fields T through reflection.

+4
source share
2 answers

You must have an attribute TupleElementNamesfor the method created by the compiler.

See this code :

public class C {
    public (int a, int b) M() {

        return (1, 2);
    }
}

What compiles:

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

You can get this attribute with this code:

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

string[] names = attr.TransformNames;
+11

, , . , ToStruct . , , , .

- ValueTuple ( ). , ItemN.


:

, , .

- , .


http://mustoverride.com/tuples_names/

+4

Source: https://habr.com/ru/post/1675126/


All Articles