void 類型方法表達式體成員允許非 void 類型的表達式 *如果其他方法* (Void-type method expression-bodied member allows expression of non-void type *if other method*)


問題描述

void 類型方法表達式體成員允許非 void 類型的表達式 如果其他方法 (Void‑type method expression‑bodied member allows expression of non‑void type if other method)

我不知道該怎麼做,我在 C# 中使用表達式體成員,我注意到一些奇怪的東西。

基本上,如果你創建一個方法表達式體成員,它有一個 void 返回類型,您仍然可以使用非 void 返回類型的方法作為表達式。

示例:

public void MethodA() { }
public void MethodB() => MethodA();

按預期工作。

public string MethodA() { return "MethodA"; }
public void MethodB() => MethodA();

編譯得很好(我沒有運行它來測試,但它編譯的事實讓我感到困惑)。這讓我很困惑,正如我在腦海中看到的那樣:

public void MethodB() { return MethodA(); }

這顯然是無效的,因為 return 語句實際上返回了一個值,這在 中是不允許的void 方法。

但是,奇怪的是以下內容無法編譯:

public void MethodC() => "MethodC";

並給出“僅賦值...”錯誤。

為什麼會發生這種情況?這是有意的,還是某種錯誤?有什麼我想念的嗎?如果它是另一種方法,是否允許表達式主體成員丟棄表達式的結果?


參考解法

方法 1:

This confuses me, as in my head I see:

public void MethodB() { return MethodA(); }

That is not actually correct; The actual syntax generated is this:

public void MethodB() { MethodA(); }

And that is perfectly fine. The return value is just ignored.

The "MethodC" code fragment isn't a method which result can be voided. It is an actual value and that needs to be assigned according to C# syntax. The same is true for regular statements: putting "MethodC"; on an empty line fails.

(by Der KommissarPatrick Hofman)

參考文件

  1. Void‑type method expression‑bodied member allows expression of non‑void type if other method (CC BY‑SA 2.5/3.0/4.0)

#return #methods #function #expression #C#






相關問題

如果評估的最後一個語句是 If 語句,Ruby 會返回什麼 (What is Returned in Ruby if the Last Statement Evaluated is an If Statement)

將多個參數傳遞給 javascript 並根據兩個參數 + php 循環更新 html 內容 (pass multiple parameters to a javascript and update html content bases on both parameters + php loop)

Loại Không khớp không thể chuyển đổi từ Boolean sang Int (Mảng trong phương thức tùy chỉnh) (Type Mismatch can't convert from Boolean to Int (Arrays in custom method))

C++返回一個帶有私有構造函數的類實例 (C++ return a class instance with private constructor)

ArrayList.isEmpty() 時如何返回值? (How do I return a value when ArrayList.isEmpty()?)

如何將坐標(元組)格式化為字符串? (How can I format a coordinate (tuple) as a string?)

void 類型方法表達式體成員允許非 void 類型的表達式 *如果其他方法* (Void-type method expression-bodied member allows expression of non-void type *if other method*)

paypal動態退貨地址 (paypal dynamic return address)

讓兩個類進行交互 (getting two classes to interact)

在 C++ 中返回“this”? (return "this" in C++?)

Java:枚舉的不同返回類型 (Java: Different return type by enum)

如何檢查函數參數和類型 (How to inspect function arguments and types)







留言討論