假设我有一个系统,必须存储有多少人在战斗机A上投票,在战斗机B上有多少人投票.
比方说,比例是200:1
如何将该值存储在单个变量中,而不是将两个值(A上的选民数和B上的选民数)存储在两个变量中.
你会怎么做?
解决方法
从问题措辞的方式来看,这可能不是您正在寻找的答案,但最简单的方法是使用结构:
struct Ratio { public Ratio(int a,int b) { this.a = a; this.b = b; } public int a = 1; public int b = 1; }
你几乎肯定会想要使用属性而不是字段,你可能也想要重载==和!=,类似于:
public static bool operator ==(Ratio x,Ratio y) { if (x.b == 0 || y.b == 0) return x.a == y.a; // There is some debate on the most efficient / accurate way of doing the following // (see the comments),however you get the idea! :-) return (x.a * y.b) == (x.b / y.a); } public static bool operator !=(Ratio x,Ratio y) { return !(x == y); } public override string ToString() { return string.Format("{0}:{1}",this.a,this.b); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。