私は方法を持っています:
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) { }
}
}
}
}