我正在寻找一种将字符串转换为类型的通用方法。
例如:
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),应使用不变区域性。
我怎样才能做到这一点?
最佳答案
你可以尝试做这样的事情:
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
...
关于c# - 逆 .ToString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18011015/