2010-11-13 98 views
1
List<Object> testimonials = new List<Object>(); 
testimonials.Add(new { 
    Author = "Author 1", 
    Testimonial = "Testimonial 1" 
}); 
testimonials.Add(new { 
    Author = "Author 2", 
    Testimonial = "Testimonial 2" 
}); 
testimonials.Add(new { 
    Author = "Author 3", 
    Testimonial = "Testimonial 3" 
}); 

@ObjectInfo.Print(testimonials[DateTime.Now.DayOfYear % testimonials.Count].Author) 

給我一個錯誤CS1061:「對象」不包含「作者」如何訪問匿名類型?

如何從推薦列表中只得到作者或見證的定義?

回答

5

一種懶惰的方式是將「對象」切換爲「動態」。或者使用A Tuple泛型類型。

但IMO,你只要簡單地寫有聽到兩聲屬性的類:

public class Testimonial { 
    public string Author {get;set;} 
    public string Comment {get;set;} 
} 

並用一個列表 - 的 - 見證。

另一種方法是使用類似:

這是你的匿名類型的數組,和;

string author = arr[0].Author; 

工作正常。

+1

+1匿名類型是非常有用的,但在這種情況下,您應該定義一個嚴格的類型。 – 2010-11-13 11:58:03

0

使用隱式類型數組:

var arr = new[] 
{ 
    new { Author = "Author 1", Testimonial = "Testimonial 1" }, 
    new { Author = "Author 2", Testimonial = "Testimonial 2" }, 
    new { Author = "Author 3", Testimonial = "Testimonial 3" } 
}; 
// .ToList() if needed, however array supports indexer 

string author = arr[i].Author;