c# - 'TryParse' 或 'TryGetValue' 的示例实现

标签 c# design-patterns

<分区>

你能给我一个 .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/

相关文章:

java - 如何在 Java 中创建具有相同类型参数的方法?

c# - 为 codeDOM 文件设置文件版本

design-patterns - 异步图片上传模式

c# - 抛出异常而不是处理返回

c# - 如何使用 Azure Functions V2 函数中的 ILogger<T>?

c# - 交付静态哈希表的最佳方式 c#

javascript - 在 JavaScript 的命名空间中存储可重用常量

C# 从循环中启动线程抛出 IndexOutOfBoundsException

c# - 如何在 Linq 查询中比较字符串

c# - 从 C# 在 TableCell 中插入图像