C#中谜:实现接口 [英] C# riddle : implement interface

查看:133
本文介绍了C#中谜:实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:



这问题不是功课。而且不防水apparantly ...
我想一个关于内部表示的讨论。
套餐组成:add1000应该加1000



**请回答这个问题的精神......让这款防水将使这个问题不再没有任何理由.. **
你能打败一个纯粹的十进制表示
http://stackoverflow.com/questions/1709680/changing-internal-representation-in-runtime
更新2:见



创建实现此接口类型:

 接口i编号
{
无效add1000();
无效的SetValue(十进制D);
十进制的GetValue();
}



让我遍历尽可能快地从0到10十亿(美国十亿,所以直到10E9)在for循环:

 私有静态无效DoSomeAdding(i编号N)
{
Debug.Assert的(n.GetValue()== 0);对于(; I<百亿;长I = 0 I + = 1000)


{
n.add1000();
}

Debug.Assert的(n.GetValue()==百亿);

}



所以,你可以叫它为:

  DoSomeAdding(新YourNumberClass()); 


解决方案

像安东的解决方案,但有更多的护理: )哦,我已经改变了名字更.NET类

 公共号码:i编号
{
私人十进制值=0米;
私人INT数千= 0;

公共无效Add1000()
{
数千++;
}

无效的SetValue(十进制D)
{
值= D;
数千= 0;
}

十进制的GetValue()
{
//小心溢出的......(做乘法十进制)
值+ =数千*千米;
数千= 0;
返回值;
}
}


UPDATE :

This question is not homework. And not waterproof apparantly... I wanted a discussion about internal representation. Of course : the add1000 ought to add 1000.

**Please answer in the spirit of this question... Making this waterproof would make this question longer without no reason.. ** You can beat a pure decimal representation http://stackoverflow.com/questions/1709680/changing-internal-representation-in-runtime UPDATE 2 : see

Create a type that implements this interface :

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

so that i iterates as fast as possible from 0 to 10 billion (american billion, so till 10e9) in this for loop :

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);

    	}

So you can call it as :

DoSomeAdding(new YourNumberClass());

解决方案

Like Anton's solution, but with a bit more care :) Oh, and I've changed the names to be more .NET-like.

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;
    }
}

这篇关于C#中谜:实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆