gpt4 book ai didi

c# - 逆.ToString()

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:05 27 4
gpt4 key购买 nike

我正在寻找将字符串转换为类型的通用方法。
例如:

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/

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