gpt4 book ai didi

c# - 增加这个 try-catch 的可读性?

转载 作者:太空宇宙 更新时间:2023-11-03 18:34:57 25 4
gpt4 key购买 nike

我想知道是否有一种更美观/更易于阅读的方式来编写以下内容:

for (int i = 0; i < 100; i++)
{
// If m.GetString(i) throws an exception, continue.
// Otherwise, do stuff.
try
{
string s = m.GetString(i);
continue;
}
catch (InvalidCastException)
{
}

// do stuff with the message that you know is not a string.
}

这是 m 的样子:

msg[0] = 10
msg[1] = "string"
msg[2] = 2.224574743
// Etc.
// Assume it's different every time.

所以当我做 m.GetString(0)在此示例中,它抛出异常,如 msg[0]uint而不是 string .这就是我用来获取类型的方法,因为 m不包含 GetType,我无法编辑 m。

m 是类 Message 的一个实例在我无法编辑的库中。

然而,尽管这工作得很好,但故意创建异常感觉效率低下(当然对读者不友好),即使它在 try-catch 中也是如此。 , 以获得类型。

有没有更好的方法,还是我坚持这样做?

编辑: 好的,我研究了 Message再上一些课(我本应该开始的,我很抱歉)。这是一个IEnumerable<object>

最佳答案

现在我知道 m是一个 IEnumerable<object> ,我认为这可能是您最好的选择:

foreach (string s in m.OfType<string>())
{
// Process s, which can't be null.
}

漂亮而简单,它似乎可以处理您想要的所有逻辑,即它将只处理序列中的字符串项目,而忽略其他类型的所有对象。

但是正如 Servy 指出的那样,这不会处理列表中的空值,因为 null根本没有任何类型。


[在我知道 m 的类型之前我之前的回答]

我认为您可以采用以下三种方法之一:

(1) 添加一个bool TryGetString(int index, out string)任何类型的方法m在你的例子中然后做

if (m.TryGetString(i, out s)) 
// Process s (need to check for null!)

(2) 添加一个bool IsString(int index)方法并在调用 GetString() 之前调用它.

if (m.IsString(i)) 
{
s = m.GetString(i);
// Process s (need to check for null!)

(3) 或者,您可以通过类似 GetObject(int index) 的方式公开项目然后做 Iiya 建议的事情:

 string s = m.GetObject(i) as string; 

if (s != null)
// Process s

我认为 (1) 或 (3) 是最好的,尽管如果我们有更多关于 m 的信息,我们可能会建议更好的解决方案.

关于c# - 增加这个 try-catch 的可读性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16817285/

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