'Object'不包含带0参数的构造函数

3 c# constructor

在我的方法中,我有这个查询:

var query =
    _db.STEWARDSHIP
        .OrderBy(r => r.SITE.SITE_NAME)
        .Where(r => SiteId == null || r.SITE_ID == iSiteId)
        .Where(r => SiteTypeId == null || r.SITE.SITE_TYPE_VAL.SITE_TYPE_ID == iSiteTypeId)
        .Where(r => EcoregionId == null || r.SITE.ECOREGION_VAL.ECOREGION_ID == iEcoregionId)
        .Where(r => ConservationAreaId == null || r.SITE.CONSERVATION_AREA_VAL.CONSERVATION_AREA_ID == iConservationAreaId)
        .Where(r => VisitTypeId == null || r.VISIT_TYPE_VAL.VISIT_TYPE_ID == iVisitTypeId)
        .Where(r => Staff == null || r.STAFF.Contains(sStaff))
        .Where(r => Comment == null || r.VISIT_COMMENTS.Contains(sComment))
        .Select(r => new SiteVisitDetails
        {
            Id = r.STEWARDSHIP_ID,
            Name = r.SITE.SITE_NAME,
            VisitType = r.VISIT_TYPE_VAL.VISIT_TYPE_DESC,
            VisitDate = r.VISIT_DATE
        });
Run Code Online (Sandbox Code Playgroud)

这失败并出现错误:

SiteVisitDetails does not contain a constructor that takes 0 arguments

这里的课程:

public class SiteVisitDetails : ISiteVisitDetails
{

    private int _id;
    private string _name;
    private DateTime _visitDate;
    private string _visitType;

    public SiteVisitDetails(int Id, string Name, DateTime VisitDate, 
                            string VisitType)
    {
        _id = Id;
        _name = Name;
        _visitDate = VisitDate;
        _visitType = VisitType;
    }

    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public DateTime VisitDate
    {
        get { return _visitDate; }
        set { _visitDate = value; }
    }

    public string VisitType
    {
        get { return _visitType; }
        set { _visitType = value; }
    }

    public string getShortVisitDate()
    { 
        return _visitDate.ToShortDateString();
    }
}
Run Code Online (Sandbox Code Playgroud)

界面:

interface ISiteVisitDetails
{
    int Id { get; set; }
    string Name { get; set; }
    DateTime VisitDate { get; set; }
    string VisitType { get; set; }
    string getShortVisitDate;
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我需要一个带0参数的构造函数.有人可以帮我理解吗?

谢谢.

Ani*_*Ani 9

不明白为什么我需要一个带0参数的构造函数.

表达方式:

new SiteVisitDetails
{
    Id = r.STEWARDSHIP_ID,
    Name = r.SITE.SITE_NAME,
    VisitType = r.VISIT_TYPE_VAL.VISIT_TYPE_DESC,             
    VisitDate = r.VISIT_DATE
}
Run Code Online (Sandbox Code Playgroud)

是真正的简写:

new SiteVisitDetails() // Note the parantheses
{
    Id = r.STEWARDSHIP_ID,
    Name = r.SITE.SITE_NAME,
    VisitType = r.VISIT_TYPE_VAL.VISIT_TYPE_DESC,
    VisitDate = r.VISIT_DATE
}
Run Code Online (Sandbox Code Playgroud)

从语言规范:

7.6.10.1对象创建表达式

[...]对象创建表达式可以省略构造函数参数列表并括起括号,前提是它包含对象初始值设定项或集合初始值设定项.省略构造函数参数列表并括起括号等效于指定空参数列表.

换句话说,你真的试图调用的参数构造函数SiteVisitDetails类型,它不存在,当然.