小编reu*_*ben的帖子

C#类方法.如何失败并返回原因?

我确信有一种解决这个问题的"好方法",但它总是让我感到烦恼.我有一个应该返回一个对象的方法,但它的参数有一定的前提条件.这些是我无法控制的,可能因"业务逻辑"原因而失败(如果你原谅这个陈旧的术语).

该对象的返回值将为null但我也想传回原因,因此调用代码基本上可以说"我没有得到我的对象,因为没有足够的信息来构建它".

我不觉得尝试捕获是正确的方法,但在这种情况下一直使用它需要更好的方法.我在stackoverflow和教科书以及MSDN上的所有阅读似乎都集中在何时如何使用异常,但我在某种程度上未能为这种情况提出一种方法.

任何人都可以建议一种更合适的模式吗?(第一篇帖子......请原谅任何失礼)

以下是我通过示例一直在玩的示例:(请注意在// TODO注释下面抛出新的Exception行)

public static Packet Parse(string packetString)
{
    Packet returnPacket = new Packet();
    StringBuilder output = new StringBuilder();

    try
    {
        using (XmlReader reader = XmlReader.Create(new StringReader(packetString)))
        {
            XmlWriterSettings ws = new XmlWriterSettings();
            ws.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(output, ws))
            {
                string rootNodeString = string.Empty;

                // Parse the packet string and capture each of the nodes.
                while (reader.Read())
                {
                    //test root node is the correct opening node name
                    if (rootNodeString == …
Run Code Online (Sandbox Code Playgroud)

.net c# error-handling

5
推荐指数
3
解决办法
1260
查看次数

标签 统计

.net ×1

c# ×1

error-handling ×1