2013-08-02 23 views
2

我正在尋找一種將字符串轉換爲類型的一般方法。
例如:逆.ToString()

class SomeThing<T> { 

    public void Add(T value) { 
     //... 
    } 

    public void Add(string value) { 
     // Try to convert from string to T ??? 
    } 
} 

用法:

SomeThing<double> list = new SomeThing<double>(); 
list.Add(123.45); 
list.Add("234.56"); 

它應該有有特點:
- 如果類型支持從字符串皈依,將其轉換。
- 如果該類型不支持從字符串轉換,則拋出異常或返回default(T)
- 對於數字(double,int),它應該使用不變的文化。

我該如何做到這一點?

+0

添加一些使用示例......您不清楚您要完成什麼。 – xanatos

+1

重複? [通用方法轉換](http://stackoverflow.com/q/17817407/1324033) – Sayse

回答

1

你可以嘗試做這樣的事情:

public void AddRange(string value) { 
    var converter = TypeDescriptor.GetConverter(typeof(T)); 

    if (!Object.Reference(converter, null)) 
    if (converter.CanConvertFrom(typeof(String)) { 
     T result = (T) converter.ConvertFrom(value); 

     // value is converted to T; your code here 
     ... 

     return; 
    } 

    // Type T can't be obtained from String directly 
    // 1. Do it using by-ways (spesific for particular T's) 
    // 2. Use default(T) 
    // 3. Throw exception 
    ... 
1

,如果你想添加到返回默認值,你可以試試這個

class SomeThing<T> 
{ 

    public void Add(T value) 
    { 
     //... 
    } 

    public void Add(string value) 
    { 
     try 
     { 
      T typedValue; 
      typedValue = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(value); 
      //Call Add with the converted value 
      this.Add(typedValue); 
     } 
     catch 
     { 
      throw; 
     } 
    } 
} 

,使用此:

class SomeThing<T> 
{ 

    public void Add(T value) 
    { 
     //... 
    } 

    public void Add(string value) 
    { 
     try 
     { 
      T typedValue; 
      typedValue = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(value); 
      //Call Add with the converted value 
      this.Add(typedValue); 
     } 
     catch 
     { 
      this.Add(default(T)); 
     } 
    } 
} 
0

如果您需要將字符串轉換爲Double,如您的示例中所示:

String myString = "123456"; 
Double myDouble 
Double.TryParse(text, out myDouble); 

TryParse不僅在Double類型上。