【问题标题】:Assign property value automatically from other properties within an object从对象内的其他属性自动分配属性值
【发布时间】:2018-11-03 05:02:09
【问题描述】:

我有以下Class

public class BlogPost
{
    public int BlogPostId             { get; set; }
    public string BlogPostTitle       { get; set; }
    public string BlogPostDescription { get; set; }
    public int Upvotes    { get; set; }
    public int Downvotes  { get; set; }
    public int TotalVotes { get; set; }
}

你将如何自动分配TotalVotes = Upvotes - Downvotes

【问题讨论】:

    标签: c# .net class oop dynamic


    【解决方案1】:

    听起来您正在寻找calculated property。所以应该是这样的:

    public int TotalVotes
    { 
        get { return Upvotes - Downvotes; } 
    }
    

    或者,如果您使用的是 C# 6+,您可以像这样使用expression body

    public int TotalVotes => Upvotes - Downvotes;
    

    【讨论】:

    • 谢谢 Akbari,我在 microsoft docs 上遇到了一个示例,它使用类似“Lambda”的表达式来实现同样的效果,并想知道如何实现它。
    【解决方案2】:

    您只需在返回路径中编写您的操作,例如:

    public int TotalVotes { get { return Upvotes - Downvotes;} }
    

    【讨论】:

      【解决方案3】:

      其他人的答案会起作用,但我更喜欢这样的东西(C# 6.0)

      public class BlogPost
      {
          public int BlogPostId { get; set; }
          public string BlogPostTitle { get; set; }
          public string BlogPostDescription { get; set; }
          public int Upvotes { get; set; }
          public int Downvotes { get; set; }
          public int TotalVotes {get => GetTotalVotes(); }   
      
          // A method just in case if you need to do some extra calculations or validations
          private int GetTotalVotes()
          {
      
              //I am assuming the TotalVotes should not go below 0;
              //You can change it as you like
      
              int value = UpVotes - DownVotes;
      
              return value<0? 0 : value;
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        • 2017-05-23
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多