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

时光总嘲笑我的痴心妄想 提交于 2019-11-29 10:11:55

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;

As Patrick pointed out above, you can use reflection to inspect the tuple names used in the declaration of your method. But that gives you no information given that your ToStruct method signature shows no names. And, in any case, that gives you no information about tuples that will actually be passed into that method.

The runtime type is only ValueTuple (no names). The names only help at compile time, as syntactic sugar for ItemN.


From the design notes:

Name erasure at runtime

Importantly, the tuple field names aren't part of the runtime representation of tuples, but are tracked only by the compiler.

As a result, the field names will not be available to a 3rd party observer of a tuple instance - such as reflection or dynamic code.


You can read more about that at http://mustoverride.com/tuples_names/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!