2
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 + ")";
}

I get following error:

Error 2 Inconsistent accessibility: return type 'johny.Form1.CoOrds' is less accessible than method 'johny.Form1.toto()

4

2 回答 2

7

As your CoOrds class is nested within Form1, it is by default private (ie. for use only within the Form1 class). The easiest solution would be to make your CoOrds class public.

public class CoOrds{ 

public int x, y; // ...

Another alternative would be to simply un-nest the CoOrds class, namely, move the declaration of the class outside of your Form1 class entirely.

于 2013-01-05T13:27:13.747 回答
2

Original answer (before I noticed that it's a nested type)

Yes - presumably Form1 and Form1.toto() are both public - whereas Coords is private (the default accessibility for non-nested types). You can't create a method with a return type or parameter type which isn't accessible to all the code which can see the method - it doesn't make sense.

Options:

  • Make Form1 internal
  • Make Form1.toto() internal
  • Make Coords public

Personally I'd recommend making Form1 internal if you can - it's rare that a form needs to be available to other code, beyond unit tests (for which I'd use InternalsVisibleTo). Making Form1.toto() internal would be equally fine. I prefer to keep types and members as private as I can, so I'd only make Coords public as a last resort.

I'd also strongly recommend that you start following .NET naming conventions, and provide more informative names than toto(). Oh, and avoid public fields - expose properties instead. You may well want to make it immutable, too.

Having noticed that it's a nested type...

It actually looks like Coords is a nested class within Form1, which will mean it's private by default. It's unusual to want to expose a nested class - and it doesn't look like it's really tightly tied to Form1 anyway. I would suggest making it a top-level (non-nested) type in the first place.

于 2013-01-05T13:27:32.550 回答