我有以下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
?
答案 0 :(得分:2)
听起来你正在寻找calculated property。所以它应该是这样的:
public int TotalVotes
{
get { return Upvotes - Downvotes; }
}
或者,如果您使用的是C#6+,可以使用expression body,如下所示:
public int TotalVotes => Upvotes - Downvotes;
答案 1 :(得分:0)
您只需要在返回路径中编写您的操作,如:
public int TotalVotes { get { return Upvotes - Downvotes;} }
答案 2 :(得分:0)
其他人的答案会奏效,但我更喜欢这样的事情(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;
}
}