<分区>
你能给我一个 .NET“try”模式的实现示例吗?
编辑:
我不是指“try-catch”语句,而是指尝试模式,如 TryParse()
和 TryGetObjectByKey()
方法中使用的模式。
最具体的是如何处理自定义“try”模式方法中引发的异常。我应该记录它,我应该忽略它。有谁知道这些方法的实践是什么?
<分区>
你能给我一个 .NET“try”模式的实现示例吗?
编辑:
我不是指“try-catch”语句,而是指尝试模式,如 TryParse()
和 TryGetObjectByKey()
方法中使用的模式。
最具体的是如何处理自定义“try”模式方法中引发的异常。我应该记录它,我应该忽略它。有谁知道这些方法的实践是什么?
最佳答案
这是使用 TryXxx 方法的示例:
string s = Console.ReadLine();
int x;
if (int.TryParse(s, out x))
{
Console.WriteLine("You entered the valid integer {0}", x);
}
else
{
Console.WriteLine("Invalid input!");
}
下面是一个定义方法的例子:
bool TryParse(string s, out int x) // out parameter for result
{
if (!allCharactersAreValid(s))
{
x = 0;
return false;
}
// More checks...
// Parse the string...
x = 42;
return true;
}
异常处理
Most specificly what to do with rised exceptions in custom 'try' pattern methods
您的方法可能应该避免抛出任何异常 - 如果您的用户想要异常,他们会使用非 Try 版本。因此,您应该尽量避免调用在实现 TryXxx 时可能抛出的方法。然而,有些异常是不可避免的,可能会超出您的控制范围 - 例如 OutOfMemoryException
, StackOverflowException
等等...对此您无能为力,您不应该 try catch 这些异常,只需让它们传播给调用者即可。不要吞下它们,也不要记录它们 - 这是调用者的责任。
这方面的一个例子是 Dictionary<TKey, TValue>.TryGetValue
当提供给此方法的关键对象抛出异常时 GetHashCode
叫做。然后生成的异常不在 TryGetValue
中被捕获方法 - 调用者将看到异常。此代码演示了这种情况:
using System;
using System.Collections.Generic;
class Foo
{
public override int GetHashCode()
{
throw new NotImplementedException();
}
}
class Program
{
public static void Main()
{
Dictionary<object, object> d = new Dictionary<object, object>();
d["bar"] = 42;
object s;
Foo foo = new Foo();
if (d.TryGetValue(foo, out s)) // results in NotImplementedException
{
Console.WriteLine("found");
}
}
}
关于c# - 'TryParse' 或 'TryGetValue' 的示例实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3850486/