私は方法を持っています:
public void StoreNumberInSmallestType(ValueType number)
{
if (numberTypes == null)
numberTypes = new List<Type>() { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };
foreach (Type t in numberTypes)
{
try
{
var converter = TypeDescriptor.GetConverter(t);
value = converter.ConvertTo(number, t);
Type = value.GetType();
return;
}
catch (OverflowException) { }
}
}
メソッドは、変数valueが として定義されているクラス内にありますdynamic。
このように使用すると:
StoreNumberInSmallestType(Math.Pow(200, 100));
valueになってしまいInfinityます。プロセスをたどってみると、 の値numberは ではなくInfinity、科学表記法で表された結果であることがわかります。numberが変換されて内部に格納されるたびに、何か悪いことが起こっていvalueます。number正しい値を保持する理由を知っている人valueはいますか?
編集:
完全なコード サンプルを次に示します。
主要:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Class1 c1 = new Class1();
c1.StoreNumberInSmallestType(Math.Pow(200, 100));
}
}
}
クラス:
namespace ConsoleApplication1
{
public class Class1
{
List<Type> numberTypes;
dynamic value;
public Type Type { get; set; }
public void StoreNumberInSmallestType(ValueType number)
{
if (numberTypes == null)
numberTypes = new List<Type>() { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };
foreach (Type t in numberTypes)
{
try
{
var converter = TypeDescriptor.GetConverter(t);
value = converter.ConvertTo(number, t);
Type = value.GetType();
return;
}
catch (OverflowException) { }
}
}
}
}