2010-06-23 106 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 };