2008-09-21 73 views
4

我在NumbericUpDown控件上構建了一個包裝器。 包裝是通用的,可以支持int?和雙?怎麼把Decimal轉換成T?

我想寫一個方法,將執行以下操作。

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

當然在小數和雙數之間沒有鑄造?或int?所以我需要使用某種轉換方式。 我想避免切換或如果表達式。

你會怎麼做?

爲了澄清我的問題,我提供了更多的代碼...

+0

你的問題不是很清楚。 GetValue方法是包裝器的一部分嗎?或者是numericUpDown包裝器的一個實例?也許更多的代碼顯示你想要達到的目標將會有所幫助。 – 2008-09-21 11:10:22

+0

上週我問了一個[相關問題](http://stackoverflow.com/questions/63694/creating-a-math-library-using-generics-in-c)。我認爲答案可能對你的情況有效。 – Sklivvz 2008-09-21 11:01:50

回答

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