使用结构的RazorEngine中奇怪的ValueType动态绑定错误

时间:2013-03-05 18:33:18

标签: c# dynamic razor value-type

在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); }

有谁能解释这里发生了什么?

0 个答案:

没有答案