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:“对象”不包含“作者”的定义

如何从推荐列表中仅获取作者或推荐?

4

2 回答 2

5

一种懒惰的方法是将“对象”切换为“动态”。或者使用 A Tuple 泛型类型。

但是 IMO 你应该简单地编写一个具有两个属性的类:

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

并使用推荐列表。

另一种方法是使用类似的东西:

var arr = new[]{new{...},new{...}};

这是您的匿名类型的数组,并且;

string author = arr[0].Author;

会工作得很好。

于 2010-11-13T11:50:45.030 回答
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;
于 2010-11-13T12:16:28.697 回答