问题:如何将ActionLink中的匿名类型语法重写为更标准的OOP?我正在努力了解正在发生的事情。
我认为这意味着:创建一个具有单个属性id的对象,它是一个int,等于item中DinnerID的对象,这是一个晚餐。
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("Edit", "Edit", new { id=item.DinnerID }) %> |
<%: Html.ActionLink("Details", "Details", new { id=item.DinnerID })%> |
<%: Html.ActionLink("Delete", "Delete", new { id=item.DinnerID })%>
</td>
<td>
<%: item.DinnerID %>
</td>
<td>
<%: item.Title %>
</td>
我想我得到匿名类型:写下我认为发生在幕后的事情。
class Program
{
static void Main(string[] args)
{
// Anonymous types provide a convenient way to encapsulate a set of read-only properties
// into a single object without having to first explicitly define a type
var person = new { Name = "Terry", Age = 21 };
Console.WriteLine("name is " + person.Name);
Console.WriteLine("age is " + person.Age.ToString());
Person1 person1 = new Person1("Bill",55);
Console.WriteLine("name is " + person1.Name);
Console.WriteLine("age is " + person1.Age.ToString());
//person1.Name = "test"; // this wont compile as the setter is inaccessible
}
}
class Person1
{
public string Name { get; private set; }
public int Age { get; private set; }
public Person1(string name, int age)
{
Name = name;
Age = age;
}
}
非常感谢。
答案 0 :(得分:2)
除了匿名类型的属性具有公共setter以及匿名类型具有无参数构造函数之外,它几乎正在做什么。
因此更准确的等价物是:
class Person1
{
public string Name { get; set; }
public int Age { get; set; }
}
Person1 person1 = new Person1 { Name = "Bill", Age = 55 };