Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

c# 7.0 - I can't get parameter names from valuetuple via reflection in c# 7.0

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...