在 RazorEngine 中使用匿名类型模型时,我遇到了一个奇怪的动态绑定错误。我知道当模型具有匿名类型时 Razor 使用动态,因为匿名类型是内部的。这是一个重现错误的快速程序:
void Main()
{
// works fine
var model = (dynamic)new { items = new[] { Create(new { a = 2 }, 1) } };
var items = model.@items;
foreach (var item in items) {
Console.WriteLine(item.Index);
}
RazorEngine.Razor.Compile(@"
@{ var items = Model.@items; }
@foreach (var item in items) { <text>
X @item.Index
</text> } X", new { items = new[] { Create(new { a = 2 }, 1) } }.GetType(), "name");
// parse failes with RuntimeBinderException: 'System.ValueType' does not contain a definition for 'Index'
var parsed = RazorEngine.Razor.Parse(@"
@{ var items = Model.@items; }
@foreach (var item in items) { <text>
X @item.Index
</text> } X", new { items = new[] { Create(new { a = 2 }, 1) } }, "name");
Console.WriteLine(parsed);
}
public struct IndexedValue<T>
{
private readonly T _value;
private readonly int _index;
public IndexedValue(T value, int index)
{
this._index = index;
this._value = value;
}
public T Value { get { return this._value; } }
public int Index { get { return this._index; } }
}
public static IndexedValue<T> Create<T>(T item, int index) { return new IndexedValue<T>(item, index); }
谁能解释这里发生了什么?