这是摘自MSDN的示例,用于C#中泛型的协方差。
我无法打印全名,我可以知道为什么输出不打印吗?
// Simple hierarchy of classes.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Employee : Person { }
public class Print
{
// The method has a parameter of the IEnumerable<Person> type.
public static void PrintFullName(IEnumerable<Person> persons)
{
foreach (Person person in persons)
{
Console.WriteLine("Name: {0} {1}",
person.FirstName, person.LastName);
}
}
}
class Program
{
public static void Main()
{
IEnumerable<Person> employees = new List<Person>();
Person person = new Person();
person.FirstName = "nuli";
person.LastName = "swathi";
Print.PrintFullName(employees);
Console.ReadKey();
}
}
答案 0 :(得分:3)
因为您的employees
列表为空。
您应该将Person实例添加到employees
列表中,然后您会看到它已打印。
即
class Program
{
public static void Main()
{
IList<Person> employees = new List<Person>(); //you need to declare this as a List/IList to get the `Add` method
Person person = new Person();
person.FirstName = "nuli";
person.LastName = "swathi";
//add this line
employees.Add(person);
Print.PrintFullName(employees);
Console.ReadKey();
}
}
答案 1 :(得分:0)
是否有可能忘记了string.format?尝试使用此:
Console.WriteLine( String.format("Name: {0} {1}", person.FirstName, person.LastName))
代替此:
Console.WriteLine("Name: {0} {1}", person.FirstName, person.LastName);
或更妙的是:
Console.WriteLine($"Name: {person.FirstName} {person.LastName}");
ref:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
编辑:由于其是mdn示例,因此列表很可能为空。
答案 2 :(得分:0)
仅使用List,List实现IEnumerable。您的 Program 类中存在一些错误,您可以在下面找到更正的代码:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Employee : Person { }
class Print
{
// The method has a parameter of the IEnumerable<Person> type.
public static void PrintFullName(IEnumerable<Person> persons)
{
foreach (Person person in persons) {
Console.WriteLine(string.Format("Name: {0} {1}", person.FirstName, person.LastName)); // needs to format the string for it to work, hence string.format().....
}
}
}
public class Program
{
public static void Main()
{
List<Person> employees = new List<Person>(); // no need to convert it to an IEnumerable object as List already implements IEnumerable<>
Person person = new Person();
person.FirstName = "nuli";
person.LastName = "swathi";
employees.Add(person); // You have to populate the list first
Print.PrintFullName(employees);
Console.ReadLine(); // Changed from Console.ReadKey()
}
}