Why am I getting “The modifier 'virtual' is not valid for this item” error?

一笑奈何 提交于 2019-12-23 07:26:32

问题


I'm trying to create mvc application with model below: (the code is large. I think it will be more understandable for you)

public class Job
{
    public int JobId { get; set; }
    public string Name { get; set; }

    public List<Job> GetJobs()
    {
        List<Job> jobsList = new List<Job>();
        jobsList.Add(new Job { JobId = 1, Name = "Operator" });
        jobsList.Add(new Job { JobId = 2, Name = "Performer" });
        jobsList.Add(new Job { JobId = 3, Name = "Head" });
        return jobsList;
    }
}

public class Person
{
    public virtual int PersonId { get; set; }
    public string FullName { get; set; }
    public int JobId { get; set; }
    public virtual Job Job;
    public string Phone { get; set; }
    public string Address { get; set; }
    public string Passport { get; set; }
    [DataType(DataType.MultilineText)]
    public string Comments { get; set; }
}

public class PersonPaidTo : Person
{
    [Key]
    public override int PersonId { get; set; }
    public virtual List<Order> Orders { get; set; }
}

public class Head : Person
{
    [Key]
    public override int PersonId { get; set; }
    public Job Job { get; set; }
    public Head()
    {
        Job.Id = 3;
    }
}

I have an error in class Person in the field Job:

The modifier 'virtual' is not valid for this item


回答1:


Yes, this code is invalid:

public virtual Job Job;

That's declaring a field, and fields can't be virtual. You either want it to be a property:

public virtual Job Job { get; set; }

Or just a field:

// Ick, public field!
public Job Job;

(My guess is that you want the former, but both are valid C#.)




回答2:


The right way to make the field private and expose it with public property.

//Field
private Job job;

//Property
public virtual Job Job
    {
        get { return job; }
        set { job= value; }
    }


来源:https://stackoverflow.com/questions/12899606/why-am-i-getting-the-modifier-virtual-is-not-valid-for-this-item-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!