如何将字符串实现为实际类型?

发布于 2025-02-11 07:46:27 字数 579 浏览 2 评论 0原文

我正在创建一个类似的投影变量:

var projection = Builders<Items>.Projection
                            .Include(x => x.Name);

include方法采用表达式expression&lt; func&lt; tsource,object&gt;&gt;字段

我想做的是将一个名为的字符串参数转换为x.Name,能够动态地投影items的其他字段在运行时。

var key = "Name";
var projection = Builders<Items>.Projection
                         .Include(x => x."key");

I am creating a projection variable like this:

var projection = Builders<Items>.Projection
                            .Include(x => x.Name);

The Include method takes an expression Expression<Func<TSource,object>> field.

What I would like to do is to convert a string parameter named key for example to x.Name, to be able to dynamically project other fields of Items at runtime.

var key = "Name";
var projection = Builders<Items>.Projection
                         .Include(x => x."key");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

以可爱出名 2025-02-18 07:46:27

如评论作为将来参考的书面答案,您可以应用

.Include(key)

String值,即字段名称。


<代码> projectDefinition&lt; tdocument&gt; .include&lt; tdocument&gt;() ,它支持fielddefinition类型的参数,

public static ProjectionDefinition<TDocument> Include<TDocument>(this ProjectionDefinition<TDocument> projection, FieldDefinition<TDocument> field)

哪个会从String值中执行隐式铸件。

public static implicit operator FieldDefinition<TDocument>(string fieldName)

As written this answer from the comment as the future reference, you can apply

.Include(key)

Provide a string value which is the field name.


As from ProjectDefinition<TDocument>.Include<TDocument>(), it supports with the parameter of FieldDefinition type,

public static ProjectionDefinition<TDocument> Include<TDocument>(this ProjectionDefinition<TDocument> projection, FieldDefinition<TDocument> field)

which FieldDefinition<TDocument> would perform an implicit cast from the string value.

public static implicit operator FieldDefinition<TDocument>(string fieldName)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文