错误1可访问性不一致:返回类型比方法更难访问

use*_*838 12 c# access-modifiers winforms

当我建立时,VS显示错误.这是我的代码:

public Composite buildComposite(ComboBox subs, ComboBox bas)
{
    int count = 0;
    Composite a = new Composite();
    if (subs.SelectedItem != null)
    {
        foreach (Substance d in listSubstance)
        {
            if (String.Compare(d.notation, subs.Text) == 0)
            {
                count++;
                a.subs = new Substance(d);
                break;
            }
        }
    }
    if (bas.SelectedItem != null)
    {
        foreach (Base g in listBase)
        {
            if (String.Compare(g.notation, bas.Text) == 0)
            {
                count++;
                a.bas = new Base(g);
                break;
            }
        }
    }
    if (count > 0)
    {
        a.equilibrium();
        a.settypesubs(arrayDefinition);
        return a;
    }
    else
        return null;
}
Run Code Online (Sandbox Code Playgroud)

这是我的错误:

错误1可访问性不一致:返回类型"Project_HGHTM9.Composite"不如方法'Project_HGHTM9.Form1.buildComposite(System.Windows.Forms.ComboBox,System.Windows.Forms.ComboBox)'c:\ users \nguyen\documents\visual studio 2013\Projects\Project_HGHTM9\Project_HGHTM9\Form1.cs 172 26 Project_HGHTM9

D S*_*ley 46

你的Composite课不是public.您不能从公共方法返回非公共类型.

如果未指定非嵌套类的可访问性,则internal默认使用.添加public到您的Composite班级定义:

public class Composite
{
    ...
Run Code Online (Sandbox Code Playgroud)

另外,如果buildComposite没有需要进行public(这意味着它只能通过形式内部使用),那么你可以做的方法private,以及:

private Composite buildComposite(ComboBox subs, ComboBox bas)
{
    ....
Run Code Online (Sandbox Code Playgroud)


Sam*_*der 5

您试图Composite从公共方法返回类的实例,但Composite不是公共方法,因此无法返回,因为任何调用代码都无法了解该类的任何信息Composite,因为它看不到它。

让你的Composite班级公开。

public class Composite{...}
Run Code Online (Sandbox Code Playgroud)

或者使返回的方法Composite与您的类具有相同的可见性(可能是私有的):

private Composite buildComposite(ComboBox subs, ComboBox bas)
Run Code Online (Sandbox Code Playgroud)

其中哪一个合适取决于您是否需要从当前程序集外部调用该方法(或使用该类)。

默认情况下,类通常是尽可能“隐藏”的,因此对于类来说是私有的。在此处阅读有关默认可见性的更多信息