C#谜语:实现接口

更新:

这个问题不是功课。 而且不是很防水……我想讨论一下内部表征。 当然:add1000应该加1000。

**请回答这个问题的精神……使这个防水会使这个问题更长,没有任何理由.. **你可以击败纯十进制表示在运行时更改内部表示更新2:看到

创建一个实现此接口的类型:

interface INumber { void add1000(); void SetValue(decimal d); decimal GetValue(); } 

所以我在这个for循环中尽可能快地从0到100亿(十亿美元,直到10e9)迭代:

 private static void DoSomeAdding(INumber n) { Debug.Assert(n.GetValue()==0); for (long i=0; i<10000000000; i += 1000) { n.add1000(); } Debug.Assert(n.GetValue() == 10000000000); } 

所以你可以称之为:

 DoSomeAdding(new YourNumberClass()); 

就像Anton的解决方案一样,但需要更加小心:)哦,我已经将名称更改为更像.NET。

 public Number : INumber { private decimal value = 0m; private int thousands = 0; public void Add1000() { thousands++; } void SetValue(decimal d) { value = d; thousands = 0; } decimal GetValue() { // Careful of the overflow... (do multiplication in decimal) value += thousands * 1000m; thousands = 0; return value; } } 
 public Cheating : INumber { static int timesCalled = 0; public void add1000() {} public void SetValue(decimal d) {} public decimal GetValue() { if (timesCalled == 0) { timesCalled += 1; return 0; } return 1000000000; } } 
 public class JNumber : INumber { decimal num = 0; public void add1000() { num = 10000000000; } public void SetValue(decimal d) { } decimal GetValue() { return num; } } 

…作弊,但通过。

我认为你需要更多的要求。 正如所写,最快的解决方案将是:

 class MyNumberClass { bool is_ten_billion = false; int GetValue() { if(is_ten_billion) return 10000000000; is_ten_billion = true; return 0; } decimal add1000() {} void setValue(decimal d) {} } 

这样,优化器可以处理对add1000()的调用,然后完成对循环的调用。