Domanda

For anyone who is experienced with C# this issue should be easy to fix. I want to make it so that subjects can have a list of courses. There are both tutor and students in this application. Thus, I created a generic Subject that defines the properties that both Tutor_Subject and Student_Subject implement. However I am getting a weird casting error.

public interface Subject<TCourse> where TCourse : Course
{
  int SubjectId { get; set; }
  string Name { get; set; }

  ICollection<TCourse> Courses { get; set; }
}

public partial class Student_Subject :Subject<Student_Course>
{
}

public partial class Tutor_Subject :Subject <Tutor_Course>
{
}

public interface Course
{
    int CourseId { get; set; }
    string Name { get; set; }
}

public partial class Student_Course :Course
{
}

public partial class Tutor_Course :Course
{
}

Here is the issue

Cannot implicitly convert type 'Tutor_Subject' to 'Course'. An explicit conversion exists (are you missing a cast?)

Subject<Course> subject;

if(type ==1)
{
    subject = new Student_Subject();  // Error 
    courseList = subjectInfo["courses"].ToObject<IList<Student_Course>>();
}
else
{
    subject = new Tutor_Subject();  // Error
    courseList = subjectInfo["courses"].ToObject<IList<Tutor_Course>>();
}

subject.Name = subjectName;
subject.Courses = courseList.ToList();
È stato utile?

Soluzione

As of C# 4, When using generics, you have to explicitly tell the compiler that a generic type may be of a more derived type (covariant) using the out keyword inside your generic parameter definition:

http://msdn.microsoft.com/en-us/library/dd469487.aspx

public interface Subject<out TCourse> where TCourse : Course
{
   int SubjectId { get; set; }
   string Name { get; set; }
   IEnumerable<TCourse> Courses { get; set; }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top