返回空引用I型具有被期望返回的對象的C#方法。我寧願如果這種方法不拋出任何例外。當它是正確的,以C#
我的問題是,是否可以接受讓該方法返回null,因此給空校驗責任給調用者不會進一步警告?
如果被叫假定對象可以爲空,只是因爲它是引用類型? (和引用類型的默認值是零: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null)
請參閱我下面的例子
// this method is expected to return an object
public MyClass getObject()
{
MyClass myObject = null;
// Another option would be to initialize to a new instance, calling the default constructor and not setting any properties
// MyClass myObject = new MyClass(); // no null check needed by the caller, but it is a pretty useless object
try
{
// just as an example
myObject = new MyClass();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return myObject; // will return null when and exception occured
}
public class MyClass
{
public int id { get; set; }
public string name { get; set; }
}
我不相信這是一個正確或錯誤的答案,只要你保持一致,並發表評論,爲什麼你檢查它之前的值可能爲空的屬性值。 – Ralt
的可能的複製[應檢索方法的返回「空」或拋出一個異常時,就不能產生的返回值?(https://stackoverflow.com/q/175532/11683) – GSerg