gpt4 book ai didi

C# 字符串解析为变量类型

转载 作者:太空宇宙 更新时间:2023-11-03 17:07:06 24 4
gpt4 key购买 nike

我想轻松地将字符串解析为一种类型,但我不想为每种类型编写包装代码,我只想能够执行“1234”.Parse() 之类的操作并让它返回1234. 这应该适用于任何具有解析功能的类型。

最佳答案

这个技巧应该有用。它使用您自动分配给的变量的类型:

public static class StringExtensions {
public static ParsedString Parse(this string s) {
return new ParsedString(s);
}
}
public class ParsedString {
string str;
public ParsedString(string s) {
str = s;
}
public static implicit operator int(ParsedString s) {
return int.Parse(s.str);
}
public static implicit operator double(ParsedString s) {
return double.Parse(s.str);
}
public static implicit operator short(ParsedString s) {
return short.Parse(s.str);
}
public static implicit operator byte(ParsedString s) {
return byte.Parse(s.str);
}
// ... add other supported types ...
}

用法:

int p = "1234".Parse();

我更喜欢使用框架提供的方法显式解析,而不是依赖这些技巧。

关于C# 字符串解析为变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1759154/

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