cómo acceder tipo anónimo?
-
09-10-2019 - |
Pregunta
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)
Me da un error CS1061: 'objeto' no contiene una definición para 'Autor'
¿Cómo consigo sólo el autor o testimonial de la lista de testimonios?
Solución
Una forma perezosa sería interruptor de "objeto" para "dinámica". O usar una tupla tipo genérico.
Sin embargo, la OMI debería simplemente escribir una clase con escuchar dos propiedades:
public class Testimonial {
public string Author {get;set;}
public string Comment {get;set;}
}
Y el uso de una lista-de-testimonial.
Otra manera sería utilizar algo como:
var arr = new[]{new{...},new{...}};
Esta es una matriz de su tipo anon, y;
string author = arr[0].Author;
funcionaría bien.
Otros consejos
El uso conjunto implícitamente proporcionado:
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;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow