C#:我如何将类属性暴露给一个类而不是另一个类?

时间:2015-05-26 16:58:46

标签: c# properties hide visibility

我有数据合同" StudentInformation"在我的类库中,类似这样:

public class StudentInformation
{
    public int StudentId { get; set; }
    public bool CanChangeBus { get; set; }
    public List<int> AvailableBuses { get; set; }
}

public class BusChangeRequestModel
{
    public StudentInformation StudentInfo { get; set; }
    ...
    ...
}

public class BusChangeResponseModel
{
    public StudentInformation StudentInfo { get; set; }
    ...
}

Request模型在StudentId中发送,类库处理信息并填充属性&#34; CanChangeBus&#34;和&#34; AvailableBuses&#34;,然后在响应模型中返回。

我想隐藏属性&#34; CanChangeBus&#34;和&#34; AvailableBuses&#34;来自请求模型。如果我将这些属性的setter更改为&#34; internal&#34;然后通过调用应用程序无法设置属性,但它们仍然可见。如何隐藏它们以免调用应用程序的请求模型实例?

3 个答案:

答案 0 :(得分:3)

public class BasicStudentInformation
{
    public int StudentId { get; set; }
}

public class StudentInformation : BasicStudentinformation
{
    public bool CanChangeBus { get; set; }
    public List<int> AvailableBuses { get; set; }
}

public class BusChangeRequestModel
{
    public BasicStudentInformation StudentInfo { get; set; }
    ...
    ...
}

public class BusChangeResponseModel
{
    public StudentInformation StudentInfo { get; set; }
    ...
}

答案 1 :(得分:1)

使用继承。类似的东西:

public class StudentBase
{
    public int StudentId { get; set; }
}

public class StudentInformation : StudentBase
{
    public bool CanChangeBus { get; set; }
    public List<int> AvailableBuses { get; set; }
}

public class BusChangeRequestModel
{
    public StudentBase StudentInfo { get; set; }
    ...
    ...
}

public class BusChangeResponseModel
{
    public StudentInformation StudentInfo { get; set; }
    ...
}

答案 2 :(得分:0)

所以BusChangeRequest只需要查看id,那么它应该只有id。

public class StudentInformation
{
    public int StudentId { get; set; }
    public bool CanChangeBus { get; set; }
    public List<int> AvailableBuses { get; set; }
}

public class BusChangeRequestModel
{
    public int StudentId { get; set; }
}

//I don't know what is expected as a repsonse?  Is StudentInfromation really the correct response
//or is something like "Accepted", "rejected", Fail...???
public class BusChangeResponseModel
{
    public StudentInformation StudentInfo { get; set; }
}