3 c#
Let's say I have a system that must store how many people voted on fighter A and how many on fighter B.
Let's say ratio is 200:1
如何将该值存储在单个变量中,而不是将两个值(A上的选民数和B上的选民数)存储在两个变量中.
你会怎么做?
Jus*_*tin 11
从问题措辞的方式来看,这可能不是您正在寻找的答案,但最简单的方法是使用结构:
struct Ratio
{
public Ratio(int a, int b)
{
this.a = a;
this.b = b;
}
public int a = 1;
public int b = 1;
}
Run Code Online (Sandbox Code Playgroud)
您将几乎肯定要使用属性而不是字段,你可能也想重载==和!=,是这样的:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
575 次 |
| 最近记录: |