C# ';并非所有代码路径都返回值';使用';试着抓住';块
我有以下接口:C# ';并非所有代码路径都返回值';使用';试着抓住';块,c#,try-catch,C#,Try Catch,我有以下接口: //define a method to create a Stream from a generic source interface IStream { Stream GetStream(); } 及 及 //反序列化实现接口IDeserializer的JSON对象 类JsonDeserializer:IDeserializer { 私有字符串json; 公共JsonDeserializer(字符串j) {json=j;} 公共T GetObject() { 返回J
//define a method to create a Stream from a generic source
interface IStream
{
Stream GetStream();
}
及
及
//反序列化实现接口IDeserializer的JSON对象
类JsonDeserializer:IDeserializer
{
私有字符串json;
公共JsonDeserializer(字符串j)
{json=j;}
公共T GetObject()
{
返回JsonConvert.DeserializeObject(json);
}
}
我想将try和catch块添加到这两个方法中以管理异常,但是如果我这样做,并非所有代码路径都将返回一个值。我知道解决这个问题的一种方法是在try块之前重新标记并初始化变量以返回。但是,我不能初始化Stream类型的变量,因为这是一个抽象类,并且我不能初始化泛型类型T的变量。
您可以建议如何解决此问题吗?您需要找到流的具体实现,例如
内存流
,创建一个实例并返回它
或
返回null
在这种情况下,其他人可能会遇到NullReferenceException
或
让例外情况过去吧
想想看,返回一个空的流是否是一个好主意。有人会试图从中阅读,并遇到其他问题
异常不是一个坏主意,因为它让函数的用户决定要做什么。使用default(T)
,让它返回NULL
(您的流是一个引用类型)
简单的例子:
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());
}
string
和Stream
是引用类型,因此default(T)
返回NULL。
int
是一种默认值为零的值类型,因此它将返回0。对于流
:只需返回NULL
。如果您不喜欢NULL
,只需创建一个空流,如MemoryStream
,然后返回它
对于泛型类型:返回默认值,即
default(T)
。有关default
关键字的更多详细信息,请选中此项。如果出现异常,您将返回要返回的明显内容
如果没有明显的东西返回,那么这是处理该异常的错误位置。要么让异常通过,要么抛出更具体的异常
这里似乎确实如此。如何最终处理内存流
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();
}
//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);
}
}
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
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();
}