gpt4 book ai didi

c# - 其他类型的 TryParse

转载 作者:行者123 更新时间:2023-11-30 21:30:41 26 4
gpt4 key购买 nike

<分区>

我想制作一个方法 int.TryParse(string, out int number),但如果它不能解析,数字应该为 null 而不是 0。

我见过一些其他的解决方案,但似乎没有一个真正允许定义条目类型。

基本上我要问的是:

How can I change the "int" in int.TryParse to something else, e.g. int?.TryParse

    public static bool TryParse(this int? i, string input, out int? output)
{
var IsNumber = int.TryParse(input, out int result);

if (!IsNumber)
output = null;
else
output = result;
return IsNumber;
}

这是我目前所拥有的,但现在我必须制作一个 int 对象?为了使用它而不是仅仅能够直接在 int 上使用它?类型。

我有什么:

        var _string = Console.ReadLine();
int? nInt = null;
var IsNumber = nInt.TryParse(_string, out int? result);

我想要的:

        var _string = Console.ReadLine();
var IsNumber = int?.TryParse(_string, out int? result);

我检查的内容:

Convert string to nullable type (int, double, etc...)

TryParse Nullable types generically


伪答案:

public class Int
{
public static bool TryParse(string input, out int? output)
{
var IsNumber = int.TryParse(input, out int result);

if (!IsNumber)
output = null;
else
output = result;
return IsNumber;
}
}

然后可以用作

var IsNumber = Int.TryParse(_input, out int? result);

返回一个 bool 值和一个值为 int 或 null 的实例“result”。

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