[英]Covariance Generics c#
這是來自MSDN的示例,用於C#中泛型的協方差。
我無法打印FullName,我可以知道為什么不打印輸出嗎?
// 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();
}
}
因為您的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();
}
}
您是否有可能忘記了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}");
參考: https : //docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/tokens/interpolated
編輯:由於其mdn示例其更有可能的列表為空。
僅使用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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.