UPDATE The main questions remain the ones under the example, but I guess it boils down to :
**If you have a type where 99% of the values could be represented in one fast, powerfull type, and only 1% in a very heavy type, (say int vs. BigInteger) How to represent it?? **
一所学校,我们学到了很多关于内部表示的知识,但从不知道如何在运行时更改它。我的意思是:假设您有一个表示小数的类,但是您使用整数在内部表示它,直到您实际上需要比整数更大的值,并且仅更改表示形式...
我以前从未想过这一点,当想到它时,我认为这永远不会奏效,因为所有的检查都会杀死它。但是我只是做了一个测试,因为我对自己的利益太好奇了,并且确实存在更改表示方式更持久的情况:给定这个接口(interface):
interface INumber
{
void add1000();
void SetValue(decimal d);
decimal GetValue();
}
我发现这两种实现中的后者在很多情况下更强大,包括 this one我创作的内容是为了吸引尽可能多的想法(不是代表,这是社区)
1. Representation by only a decimal
public class Number1:INumber
{
private decimal d { get; set; }
public void add1000()
{
d += 1000;
}
public decimal GetValue()
{
return d;
}
public void SetValue(decimal d)
{
this.d = d;
}
}
2. Representation by a decimal and an int
public class Number2:INumber
{
private bool usedecimal;
private int i;
private decimal d;
public void add1000()
{
if (usedecimal)
{
d += 1000;
return;
}
i += 1000;
if (i > 2147480000)
{
d = i;
usedecimal = true;
}
}
public void SetValue(decimal d)
{
try
{
i = (int)d;
}
catch (OverflowException e)
{
this.d = d;
}
}
public decimal GetValue()
{
return Math.Max(i,d);
}
}
}
我的问题如下:
这好像……我失踪了,但这一定是明显的流血。谁能帮我解决这个问题?
最佳答案
If you have a type where 99% of the values could be represented in one fast, powerfull type, and only 1% in a very heavy type, (say int vs. BigInteger) How to represent it??
BigInteger 实现通常就是这样做的;他们将所有内容保存在整数或长整数中,直到某些内容溢出,然后才进行更重的实现。
有很多方法可以表示它。我喜欢的一个模式是:
public abstract class Thing
{
private class LightThing : Thing
{ ... }
private class HeavyThing : Thing
{ ... }
public static Thing MakeThing(whatever)
{ /* make a heavy or light thing, depending */ }
... etc ...
}
Are there guidelines for mixed representations, when to use them, when not?
当然。我们可以很容易地编译出这样的列表。这种技术在以下情况下是有意义的:
(1) 轻量级实现比重量级实现轻得多
(2) 典型用法大部分时间落入轻量级代码路径
(3) 与重量级解决方案的成本相比,检测转换的成本不是显着的成本
(4) 为了实现以客户为中心的现实绩效目标,需要更复杂的二表示解决方案。
How to have a hunch when a mixed represtenation can be faster without benchmarking?
别。基于预感做出绩效决策是在事实之前进行推理。插入基于现实、以客户为中心、数据驱动的分析的绩效决策,而不是凭直觉。如果这些年来我学到了关于性能分析的一件事,那就是我的预感通常是错误的。
Any examples?
BigInteger 的任意数量的实现。
Any patterns?
打败了我。我不太喜欢记住模式分类法。
Any ideas on the matter?
往上看。
关于c# - 在运行时更改内部表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1709680/