Why can't I pass List as a parameter to a method that accepts List<object>?

前端 未结 8 417
北恋
北恋 2021-01-11 13:31

The following code gives me this error:

Cannot convert from \'System.Collections.Generic.List\' to \'System.Collections.Generic.List\'.

8条回答
  •  被撕碎了的回忆
    2021-01-11 13:44

    Instead of passing List which does not work for the reasons above, could you not simply pass just an object reference then get the list type afterwards, kinda like...

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1 {
    
        class Customer {
            public int id;
            public string name;
        }
    
        class Monkey {
    
            public void AcceptsObject(object list) {
    
                if (list is List) {
                    List customerlist = list as List;
                    foreach (Customer c in customerlist) {
                        Console.WriteLine(c.name);
                    }
                }
            }
        }
    
        class Program {
            static void Main(string[] args) {
    
                Monkey monkey = new Monkey();
                List customers = new List { new Customer() { id = 1, name = "Fred" } };
                monkey.AcceptsObject(customers);
                Console.ReadLine();
            }
        }
    }
    

提交回复
热议问题