sách gpt4 ai đã đi

Nghịch đảo của .ToString()

In lại 作者:太空宇宙 更新时间:2023-11-03 11:00:05 28 4
mua khóa gpt4 Nike

我正在寻找将字符串转换为类型的通用方法。
Ví dụ:

class SomeThing {

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

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

cách sử dụng:

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

它应该有的特点:
- 如果类型支持从字符串转换,则进行转换。
- 如果类型不支持从字符串转换,则抛出异常或返回 default(T).
- 对于数字(double,int),它应该使用不变的文化。

Tôi có thể làm điều này bằng cách nào?

1 Câu trả lời

你可以尝试做这样的事情:

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/

28 4 0
太空宇宙
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com