如何将十进制转换为T进制?

4
我已经为NumericUpDown控件创建了一个包装器。 这个包装器是通用的,可以支持int?和double?。
我想编写一个方法,实现以下功能。
public partial class NullableNumericUpDown<T> : UserControl where T : struct
{
  private NumbericUpDown numericUpDown;


  private T? Getvalue()
  {
    T? value = numericUpDown.Value as T?; // <-- this is null :) thus my question
    return value;
  }}

当然,十进制和双精度浮点型之间没有转换方式?或者整型和双精度浮点型之间也没有?所以我需要使用一定的转换方法。我想要避免使用switch或if表达式。
你会怎么做?
为了阐明我的问题,我提供了更多的代码...

我上周问了一个相关的问题。我认为这个答案可能在你的情况下有效。 - Sklivvz
我没有看到它如何有用。 我想以某种方式使用转换器逻辑。 - ArielBH
你的问题不够清晰。GetValue方法是包装器的一部分吗?还是numericUpDown是包装器的一个实例?也许展示一些更多的代码可以帮助说明你想要实现什么。 - Paul Batum
你可以返回类似于 MathProvider<T> 的东西。 - Sklivvz
我认为问题在于如何创建这个“类似”的东西。 - aku
3个回答

5

目前不清楚您将如何使用它。如果您想要双倍创建GetDouble()方法,对于整数-GetInteger()。

编辑:

好的,现在我认为我明白了您的用例

尝试这个:

using System;
using System.ComponentModel;

static Nullable<T> ConvertFromString<T>(string value) where T:struct
{
    TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
    if (converter != null && !string.IsNullOrEmpty(value))
    {
        try
        {
            return (T)converter.ConvertFrom(value);
        }
        catch (Exception e) // Unfortunately Converter throws general Exception
        {
            return null;
        }
    }

    return null;
}

...

double? @double = ConvertFromString<double>("1.23");
Console.WriteLine(@double); // prints 1.23

int? @int = ConvertFromString<int>("100");
Console.WriteLine(@int); // prints 100

long? @long = ConvertFromString<int>("1.1");
Console.WriteLine(@long.HasValue); // prints False

如果你只需要double和int,为什么需要泛型? - aku
阿库,很酷,但不幸的是DoubleConveter不支持小数 :| - ArielBH
我不明白你在说什么。为什么要使用DoubleConverter?这段代码是有效的 decimal? @decimal = ConvertFromString<decimal>("99999999999999999999999"); - aku
和这个:ConvertFromString<decimal>("1.1") - aku

0

由于这个方法总是会返回结果

numericUpDown.Value

你没有理由将该值转换为除了十进制以外的任何东西。你是在试图解决你没有的问题吗?


0
public class FromDecimal<T> where T : struct, IConvertible
{
    public T GetFromDecimal(decimal Source)
    {
        T myValue = default(T);
        myValue = (T) Convert.ChangeType(Source, myValue.GetTypeCode());
        return myValue;
    }
}

public class FromDecimalTestClass
{
    public void TestMethod()
    {
        decimal a = 1.1m;
        var Inter = new FromDecimal<int>();
        int x = Inter.GetFromDecimal(a);
        int? y = Inter.GetFromDecimal(a);
        Console.WriteLine("{0} {1}", x, y);

        var Doubler = new FromDecimal<double>();
        double dx = Doubler.GetFromDecimal(a);
        double? dy = Doubler.GetFromDecimal(a);
        Console.WriteLine("{0} {1}", dx, dy);
    }
}

private T? Getvalue()
{
  T? value = null;
  if (this.HasValue)
    value = new FromDecimal<T>().GetFromDecimal(NumericUpDown);
  return value;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接