在
this question中建议,我可以使用.Cast< object>将一个泛型集合向上转换为一组对象.在
reading up a bit on
.Cast<>
之后,我仍然无法将它作为一个通用集合投射到另一个通用集合中.以下为什么不工作?
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","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; } } }
解决方法
你在滥用
Cast<T>
.
首先,这里:
IEnumerable<string> items = strings.Cast<object>();
当你调用strings.Cast< object>()时,这将返回IEnumerable< object>,而不是IEnumerable< string>.但是,集合中的项仍然是字符串,但保留在对象的引用中.
稍后,当您想将此传递给一个采用List< object>的方法时,您需要转换您的IEnumerable< T>进入IList< T>.这很容易就像这样:
// Cast to IEnumerabe<object> then convert to List<object> ProcessCollectionDynamicallyWithReflection(strings.Cast<object>().ToList());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。