2010-06-23 102 views
0

问题:如何将ActionLink中的匿名类型语法重写为更标准的OOP?我试图理解发生了什么。ASP.NET MVC中的匿名类型语法

我认为它的意思是:用一个属性id创建一个对象,它是一个int,等于Item中DinnerID的对象,它是一个Dinner。

<% 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

绝对没有错匿名类型。为什么要打造一个拥有1个属性的类,'id'。?这是匿名类型最适合的。 – 2010-06-23 03:04:34

+1

任何一种方法(匿名或命名类)都适用。 MVC框架只是使用反射来获取属性名称/值。 – Ryan 2010-06-23 04:31:03

回答

2

除了匿名类型的属性具有public setter,匿名类型具有无参数的构造函数之外,它几乎完成了它的工作。

所以更准确的当量是:

class Person1 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

Person1 person1 = new Person1 { Name = "Bill", Age = 55 };