سؤال

Each partial class has an implementation of Courses event though it is not shown.

public abstract class  Subject<T> where T : Course
{

ICollection<T> Courses { get; set; }
}
 public partial class Student_Subject :Subject<Student_Course >
{}
 public partial class Tutor_Subject :Subject <Tutor_Course>
{}
 public abstract class  Course {}

 public partial class Student_Course Course {}

 public partial class Tutor_Course : Course {}

I am getting a error.

        Subject<Course> subject;
  if(type ==1)
   {
       subject = new Student_Subject(); // error

Why can I not convert this type. Student_Subject is a Subject. I am new to C# and I have spent the whole day working on this. I originally tried with interfaces, however in-order to get that to work, I had to make it co-variant allowing only read access. (If I am not mistaken). Am I missing something , is there a better way to implement this desire functionality

هل كانت مفيدة؟

المحلول

Difference between Course and Student_Course probably isn't able to be implicitly converted. What you could do is use dynamic:

dynamic subject;

if (id == 1)
   subject = new Student_Subject();

Or you can use certain design patterns around this; for instance, use a wrapper class around the various types of student classes or have custom interfaces, which you can check if one instance implements via:

object course;

//init logic

if (subject is IStudentSubject)
{
   // Convert and do something with
}

There are ways around it that are convenient.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top