나는이 라인에서 컴파일러 오류를 받고 있어요 :이 예제에서 .NET 4.0 공분산이 작동하지 않는 이유는 무엇입니까?
RenderLookup(Cars);
RenderLookup(Employees);
Error 2 Argument 1: cannot convert from 'Demo.MyList<Demo.Car>' to 'System.Collections.Generic.IEnumerable<Demo.KeyedBase>' Program.cs 85 26 Demo
Error 4 Argument 1: cannot convert from 'Demo.MyList<Demo.Employee>' to 'System.Collections.Generic.IEnumerable<Demo.KeyedBase>' Program.cs 86 26 Demo
거래 무엇입니까? 나는 .NET 4.0이 이것을 처리 할 것이라고 생각했다. 내가 뭘 놓치고 있니?
using System;
using System.Collections.Generic;
namespace Demo
{
public interface KeyedBase
{
int Key { get; }
string Description { get; }
}
public class MyList<T> : Dictionary<int, T> where T : KeyedBase
{
public void Add(T itm)
{
Add(itm.Key, itm);
}
}
public class Car : KeyedBase
{
private readonly int _ID;
private readonly string _Description;
public Car(int ID, string Description)
{
_ID = ID;
_Description = Description;
}
public int Key
{
get { return _ID; }
}
public string Description
{
get { return _Description; }
}
}
public class Employee : KeyedBase
{
private readonly int _ID;
private readonly string _FirstName;
private readonly string _LastName;
public Employee(int ID, string FirstName, string LastName)
{
_ID = ID;
_FirstName = FirstName;
_LastName = LastName;
}
public int Key
{
get { return _ID; }
}
public string Description
{
get { return _LastName + ", " + _FirstName; }
}
}
class Program
{
private static void RenderLookup(IEnumerable<KeyedBase> Lookup)
{
Console.WriteLine("Choose:");
foreach (var itm in Lookup)
{
Console.WriteLine("{0} : {1}", itm.Key, itm.Description);
}
}
static void Main(string[] args)
{
var Cars = new MyList<Car> { new Car(1, "Subaru"), new Car(2, "Volswagen") };
var Employees = new MyList<Employee>
{
new Employee(1, "Mickey", "Mouse"),
new Employee(2, "Minnie", "Mouse")
};
RenderLookup(Cars);
RenderLookup(Employees);
}
}
}
오류를 줄 수있는 줄을 알려 주실 수 있습니까? 그것은 더 쉬울 것입니다 ... – Marco