设置匿名类型的属性名称

编程入门 行业动态 更新时间:2024-10-15 14:13:48
本文介绍了设置匿名类型的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我们说我有下面这段代码:

Let's say I have the following piece of code:

string SomeConst = "OtherName"; var persons = GetPersons(); //returns list of Person var q = persons.Select(p => new { SomeConst = p.Name });

基本上,我期望在问:匿名类型与序列命名属性 中文别名而非 SomeConst 。 我怎样才能实现这样的行为?

Basically I'd expect to have in q sequence of anonymous type with the property named OtherName and not SomeConst. How can I achieve such a behaviour?

推荐答案

您不能这样做。匿名类型的属性名称必须在编译时是已知的。 ?到底为什么你需要做的。

You can't do that. The names of the properties of an anonymous type must be known at compile time. Why exactly do you need to do that?

您可以通过创建一个字典,而不是匿名对象序列达到类似的效果:

You could achieve a similar effect by creating a sequence of dictionaries instead of anonymous objects:

string SomeConst = "OtherName"; var persons = GetPersons(); //returns list of Person var q = persons.Select(p => new Dictionary<string, string> { { SomeConst, p.Name } });

更多推荐

设置匿名类型的属性名称

本文发布于:2023-11-07 00:39:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565081.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   名称   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!