【问题标题】:C#: How can I expose a class property to one class but not to another?C#:如何将类属性暴露给一个类而不暴露给另一个类?
【发布时间】:2015-08-08 11:43:40
【问题描述】:

我的类库中有一个数据协定“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,类库处理信息并填充属性“CanChangeBus”和“AvailableBuses”,然后在响应模型中返回。

我想从请求模型中隐藏属性“CanChangeBus”和“AvailableBuses”。如果我将这些属性的设置器更改为“内部”,则无法通过调用应用程序设置属性,但它们仍然可见。如何在调用应用程序的请求模型实例时隐藏它们?

【问题讨论】:

  • 要真正隐藏它们,您应该为不暴露它们的请求使用不同的类。
  • 使用继承 + 保护而不是公共

标签: c# properties hide visibility


【解决方案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】:

    所以 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; }
    }
    

    【讨论】:

      【解决方案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; }
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 1970-01-01
        • 1970-01-01
        • 2010-11-22
        相关资源
        最近更新 更多