我在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;
}}
Run Code Online (Sandbox Code Playgroud)
当然小数和双数之间没有强制转换?还是int?所以我需要使用某种转换方式.我想避免切换或if表达式.
你会怎么做?
为了澄清我的问题,我提供了更多代码......
目前尚不清楚你将如何使用它.如果你想双重创建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
Run Code Online (Sandbox Code Playgroud)