gpt4 book ai didi

c# - 如何从十进制转换为T?

转载 作者:太空狗 更新时间:2023-10-30 01:12:32 24 4
gpt4 key购买 nike

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

decimal 和 double 之间当然没有转换?还是整数?所以我需要使用某种转换方式。我想避免使用 switch 或 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

关于c# - 如何从十进制转换为T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/110763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com