'Not all code paths return a value' 使用 'try and catch' 块

'Not all code paths return a value' using 'try and catch' block

我有以下接口:

//define a method to create a Stream from a generic source
interface IStream
{
    Stream GetStream();
}

//define a method to deserialize an object from a stream
interface IDeserializer<T>
{
    T GetObject();
}

以及实现它们的以下两个 classes:

//create a new Stream from a URL source
class UrlReader : IStream
{
    private String url;

    public UrlReader(String u)
    { url = u; }

    public Stream GetStream()
    {
        using (var client = new WebClient())
        {
            Stream stream = client.OpenRead(url);
            return stream;
        }
    }
}

//deserialize a JSON object implementing the interface IDeserializer
class JsonDeserializer<T> : IDeserializer<T>
{
    private String json;

    public JsonDeserializer(String j)
    { json = j; }

    public T GetObject()
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
}

我想将 try 和 catch 块添加到这两种方法中以管理异常,但是如果我这样做,并非所有代码路径都会 return 一个值。我知道解决此问题的一种方法是在 try 块之前将变量 decalre 并初始化为 return 。但是我无法初始化 Stream 类型的变量,因为这是一个抽象 class 并且我无法初始化泛型 T 的变量。 你能告诉我如何解决这个问题吗?

您要么需要找到 Stream 的具体实现,例如 MemoryStream,创建一个实例,然后 return 它

return null 在这种情况下,其他人可能 运行 变成 NullReferenceException

尽管例外。

考虑一下,return使用空流是否是个好主意。有人会尝试阅读它并 运行 进入其他问题。

异常并不是一个坏主意,因为它将做什么的决定留给了函数的用户。

default(T)让它returnNULL(你的Stream是引用类型)

简单示例:

class test<T>
{
    public T Return()
    {
        return default(T);
    }
}

void Main()
{
    Console.WriteLine ((new test<string>()).Return());
    Console.WriteLine ((new test<int>()).Return());
    Console.WriteLine ((new test<Stream>()).Return());
}

这将输出

null
0
null

stringStream 是引用类型,因此 default(T) returns NULL。 int 是默认值为零的值类型,因此它将 return 0.

对于 Stream:只是 return NULL。如果您不喜欢 NULL,只需创建一个空流,例如 MemoryStream 和 return。

对于泛型类型:return默认值,即default(T)。有关 default 关键字的更多详细信息,请查看此 link.

你return明显的事情return在异常的情况下。

如果 return 没有明显的东西,那么这是处理该异常的错误位置。要么让异常通过,要么抛出更具体的异常。

这里似乎确实是这种情况。

最终处理内存流怎么样?

public class W : I
    {
        public Stream GetStream()
        {
            MemoryStream ms = new MemoryStream();

            try
            {
                var connectStream = new WebClient().OpenRead("http://www.google.com");
                if (connectStream != null)
                {
                    connectStream.CopyTo(ms);
                }
            }
            catch (Exception)
            {
                throw;
            }

            return ms;
        }
    }

    public interface I
    {
        Stream GetStream();
    }