如何获取C#具名元组的自定义属性名称而非默认Item名称?
获取C#具名元组的实际属性名称
具名元组的名称是编译时语法糖,运行时底层字段仍以Item1、Item2命名,真实的元素名称被存储在TupleElementNamesAttribute特性中,因此可以通过反射读取该特性来获取实际名称。
解决方案一:读取TupleElementNamesAttribute特性(推荐)
修改你的GetProps方法,通过反射获取特性中存储的元素名称:
using System; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; public class Program { public static void Main() { Console.WriteLine("Hello World: {0}", string.Join(", ", GetProps<(int Site, int Location)>())); } public static string[] GetProps<T>() { var tupleType = typeof(T); var elementNamesAttr = tupleType.GetCustomAttribute<TupleElementNamesAttribute>(); return elementNamesAttr?.TransformNames ?? tupleType.GetFields().Select(f => f.Name).ToArray(); } }
运行结果为:Hello World: Site, Location
该方法是官方设计的具名元组名称获取方式,兼容性好,不会出现名称冲突问题。
解决方案二:过滤编译器生成的具名属性
具名元组编译后会同时生成ItemX字段和对应名称的属性,可通过过滤掉Item开头的属性来获取名称:
public static string[] GetProps<T>() { return typeof(T).GetProperties() .Where(p => !p.Name.StartsWith("Item")) .Select(p => p.Name) .ToArray(); }
注意:如果元组元素名称本身以Item开头(如(int Item1, int Item2)),此方法会失效,因此不推荐作为通用方案。
内容的提问来源于stack exchange,提问作者ADM-IT
相关产品推荐
相关产品推荐

