Было предложено в this question, что я мог бы наложить общую коллекцию вверх на коллекцию объектов с помощью .Cast<object>
. После reading up a bit on .Cast<>
я до сих пор не могу получить его в общей коллекции, чтобы добавить в другую коллекцию. Почему не работает следующее?Почему не strings.Cast <object> листинг Список <string> в список <object>?
using System.Collections.Generic;
using System.Linq;
using System;
namespace TestCast2343
{
class Program
{
static void Main(string[] args)
{
List<string> strings = new List<string> { "one", "two", "three" };
//gives error: cannot convert from 'System.Collections.Generic.List<string>'
//to 'System.Collections.Generic.List<object>'
//IEnumerable<string> items = strings.Cast<object>();
//this works
strings.Cast<object>();
//but they are still strings:
foreach (var item in strings)
{
System.Console.WriteLine(item.GetType().Name);
}
//gives error: cannot convert from 'System.Collections.Generic.List<string>'
//to 'System.Collections.Generic.List<object>'
ProcessCollectionDynamicallyWithReflection(strings);
Console.ReadLine();
}
static void ProcessCollectionDynamicallyWithReflection(List<object> items)
{
//...
}
}
}
Ответ:
Спасибо Рид, вот код, который я должен работать:
using System.Collections.Generic;
using System.Linq;
using System;
namespace TestCast2343
{
class Program
{
static void Main(string[] args)
{
List<string> strings = new List<string> { "one", "two", "three" };
List<int> ints = new List<int> { 34, 35, 36 };
List<Customer> customers = Customer.GetCustomers();
ProcessCollectionDynamicallyWithReflection(strings.Cast<object>().ToList());
ProcessCollectionDynamicallyWithReflection(ints.Cast<object>().ToList());
ProcessCollectionDynamicallyWithReflection(customers.Cast<object>().ToList());
Console.ReadLine();
}
static void ProcessCollectionDynamicallyWithReflection(List<object> items)
{
foreach (var item in items)
{
Console.WriteLine(item.GetType().Name);
}
}
}
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string Location { get; set; }
public string ZipCode { get; set; }
public static List<Customer> GetCustomers()
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer { FirstName = "Jim", LastName = "Jones", ZipCode = "23434" });
customers.Add(new Customer { FirstName = "Joe", LastName = "Adams", ZipCode = "12312" });
customers.Add(new Customer { FirstName = "Jake", LastName = "Johnson", ZipCode = "23111" });
customers.Add(new Customer { FirstName = "Angie", LastName = "Reckar", ZipCode = "54343" });
customers.Add(new Customer { FirstName = "Jean", LastName = "Anderson", ZipCode = "16623" });
return customers;
}
}
}
Mesleading: код НЕ превращает 'IEnumerable
Да. Это не бросок, это полная конверсия. Enumerable.Cast аналогичен, хотя, опять же, не просто одной операции кастинга, а скорее создает новую перечислимую последовательность. –