如何使用剃刀语法转换为对象

use*_*643 3 asp.net-mvc razor

@using System.Data
@model DataTable

@foreach (var row in Model.Rows)
{
   @row[]  // how do you cast this to a object?
}
Run Code Online (Sandbox Code Playgroud)

如何使用Razor语法将@row转换为对象?

iap*_*dev 7

你可以编写常见的C#代码:

@foreach (YourType row in Model.Rows)
{
     ...
}
Run Code Online (Sandbox Code Playgroud)

要么

@foreach (var row in Model.Rows)
{
    YourType casted = (YourType)row;
    ...
}
Run Code Online (Sandbox Code Playgroud)

或者如果您不确定它是否可浇铸:

@foreach (var row in Model.Rows)
{
    YourType casted = row as YourType;

    if (casted != null)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*ell 5

我今天遇到了这个问题。我使用的解决方案是使用括号:

@((YourType) row)
Run Code Online (Sandbox Code Playgroud)