c# - 如何访问匿名类型?

标签 c# anonymous-types webmatrix

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

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

最佳答案

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

但是在我看来,您应该简单地编写一个具有两个属性的类:

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

并使用推荐列表。

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

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

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

string author = arr[0].Author;

可以正常工作。

关于c# - 如何访问匿名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4172350/

相关文章:

java - 在 Java 中传递的可选匿名参数

c# - 使用聚合连接 linq 将结果放入 POCO

c# - 网站速度测试。 gzip 有问题吗?

c# - 包装值扩展方法/运算符

c# - 断言相等匿名类型

c# - 在列表中创建自定义 linq 列名称

php - 在实时 Windows 服务器上安装 Wordpress?

c# - WebMatrix razor C# WebSecurity 登录但 Web.Security.IsAuthenticated 未返回正确的检查

php - 数据库显示错误 - Webmatrix

C#:如何构造这个要被覆盖的方法