C#riddle:实现接口

Pet*_*ter -1 c#

更新:

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

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

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

interface INumber
    {
        void add1000();
        void SetValue(decimal d);
        decimal GetValue();         
    }
Run Code Online (Sandbox Code Playgroud)

所以我在这个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);

        }
Run Code Online (Sandbox Code Playgroud)

所以你可以称之为:

DoSomeAdding(new YourNumberClass());
Run Code Online (Sandbox Code Playgroud)

Aus*_*nen 13

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我想有人可能会说这不是*作弊*而只是一个早期的解决方案,用于测试驱动的设计,它通过了唯一的测试接口. (5认同)

Jon*_*eet 6

就像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;
    }
}
Run Code Online (Sandbox Code Playgroud)