2017-06-12 40 views
0

返回空引用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; } 
} 
+4

我不相信這是一個正確或錯誤的答案,只要你保持一致,並發表評論,爲什麼你檢查它之前的值可能爲空的屬性值。 – Ralt

+1

的可能的複製[應檢索方法的返回「空」或拋出一個異常時,就不能產生的返回值?(https://stackoverflow.com/q/175532/11683) – GSerg

回答

0

是的,你可以返回null同樣你正在做什麼,在這種情況下,責任在於給呼叫者在嘗試訪問對象的任何屬性之前檢查是否爲空。使用C#6語法

muobject?.Age 

可以使用的每個模式Null Object Pattern;在這種情況下,您返回空對象而不是返回null。因此,即使調用者的錯誤就不會與NullRefException炸燬。爲了驗證目的,你可以檢查像if(string.IsNullOrEmpty(myobject.name)) ....

+2

他當然可以,但他詢問是否返回空值或更好地拋出異常/返回一個未確定對象。如果他記錄行爲並且與類似的方法一致,那麼任何方法都可以。 –

相關問題