怎么把Decimal转换成T?

时间:2020-03-06 14:30:15  来源:igfitidea点击:

我已经在NumbericUpDown控件上构建了一个包装器。
包装器是通用的,可以支持int吗?并加倍?

我想编写一个方法来执行以下操作。

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或者表达式。

你会怎么做?

为了澄清我的问题,我提供了更多代码...

解决方案

目前尚不清楚我们将如何使用它。
如果要双重创建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

由于此方法将始终返回的结果

numericUpDown.Value

我们没有理由将值转换为十进制以外的任何值。我们是否正在尝试解决自己没有的问题?

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