简体   繁体   English

通过使用过程生成的变量标识符返回值

[英]Return value by using procedurally generated variable identifier

An example: 一个例子:

@foreach (var p in products)
{
    <a href="/@(p.Path)">@translations.@(p.TextId)</a>
}

The @translations.@(p.textId) does not work, but that is along the lines what I think of as the procedurally generated variable identifier . @translations.@(p.textId)不起作用,但这与我认为是程序生成的变量标识符 @translations.@(p.textId)

I imagine, to return value that would correspond to, as if I'd have written: @translations.helloworldproduct or @translations.otherproduct . 我想返回一个与之对应的值,就好像我已经写过了: @translations.helloworldproduct@translations.otherproduct

And in my translations database, I'd have: helloworldproduct = "Hello, World!" 在我的translations数据库中,我将拥有: helloworldproduct = "Hello, World!" and otherproduct = "Yet another product test." and otherproduct = "Yet another product test." .

The HTML result would be: HTML结果将是:

<a href="/products/1">Hello, World!</a>
<a href="/products/2">Yet another product test.</a>

Is anything like this possible? 这样有可能吗?

That won't work because you're essentially trying to pull the equivalent of a JS eval . 那是行不通的,因为您实际上是在尝试拉出JS eval的等效项。 Well ok, you can get it to work, but you'd have to use reflection and it's both ugly and slow. 好吧,您可以使用它,但是您必须使用反射,它既丑陋又缓慢。

You'd be much better off giving translations an indexer, such as the one provided for free with the generic Dictionary<TKey, TValue> . translations一个索引器会更好一些,例如通用的Dictionary<TKey, TValue>免费提供的索引器。 (Note I'm not sure what type translations is. I'm assuming it's either an anonymous type or some concrete class with properties.) Then you could use the indexer: (请注意,我不确定类型translations是什么。我假设它是匿名类型或具有属性的某些具体类。)然后可以使用索引器:

@translations[p.TextId]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM