[英]Error : Inconsistent accessibility: return type is less accessible than method '
[英]I had this error: Error 2 Inconsistent accessibility: return type 'johny.Form1.CoOrds' is less accessible than method 'johny.Form1.toto()
class CoOrds
{
public int x, y;
public CoOrds() {
x = 0;
y = 0;
}
public CoOrds(int x, int y) {
this.x = x;
this.y = y;
}
}
public CoOrds toto() {
CoOrds B = new CoOrds(3, 2);
return B;
}
private void result_Click(object sender, EventArgs e) {
l6.Text = "";
CoOrds D = new CoOrds();
D = toto();
l6.Text = "(" + D.x + "," + D.y + ")";
}
我收到以下錯誤:
Error 2 Inconsistent accessibility: return type 'johny.Form1.CoOrds' is less accessible than method 'johny.Form1.toto()
由於您的CoOrds
類嵌套在Form1
,因此默認為private
(即僅在Form1
類中使用)。 最簡單的解決方案是將您的CoOrds
類public
。
public class CoOrds{
public int x, y; // ...
另一種方法是簡單地取消嵌套CoOrds
類,即完全將類的聲明移到Form1
類之外。
原始答案 (在我注意到它是嵌套類型之前)
是的 - 大概Form1
和Form1.toto()
都是公共的 - 而Coords
是private
(非嵌套類型的默認可訪問性)。 您不能創建一個返回類型或參數類型的方法,所有可以看到該方法的代碼都無法訪問它 - 它沒有意義。
選項:
Form1
內部化 Form1.toto()
內部 Coords
公開 我個人建議如果可以的話,將Form1
設為內部 - 除了單元測試(我使用InternalsVisibleTo
)之外,很少需要將表單提供給其他代碼。 使Form1.toto()
內部同樣好。 我更喜歡把類型和成員盡可能地保密,所以我只會將Coords
公之於眾。
我還強烈建議您開始遵循.NET命名約定,並提供比toto()
更多信息的名稱。 哦,避免使用公共字段 - 而是公開屬性。 您也可能希望將其變為不可變。
注意到它是一個嵌套類型......
它實際上看起來像Coords
是Form1
的嵌套類,這意味着它默認是私有的。 想要暴露一個嵌套類是不尋常的 - 而且看起來它與Form1
的關系並不緊密。 我建議首先將它設為頂級(非嵌套)類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.