简体   繁体   中英

Public property of private class

I have a NavigationModel class which implements site navigation. Internally there is a private implementation of NavigationNode which I want to be able to declare within the NavigationModel but not outside of it. How would I accomplish this? When I do the following:

public class NavigationModel
{
    public List<NavigationNode> NavigationNodes { get; set; }
    public NavigationModel()
    {

    }

    private class NavigationNode
    {

    }
}

The property tells me:

Inconsistent accessibility: property type 'List' is less accessible than property 'NavigationModel.NavigationNodes'

The error is raised because by declaring NavigationModel as public, you create a public interface that is used to access NavigationModel. Part of this interface are the signatures of the public methods or properties. By that, you'd publish class NavigationNode that is supposed to be private - hence the error.

In order to fix this, you could create a public interface that only contains the parts of NavigationNode that you want to publish. If you do not want to publish anything, the interface is empty. The following sample shows the basic components:

  • Public interface INavigationNode .
  • Property of type List<INavigationNode> .
  • Private class NavigationNode that implements the interface.

public interface INavigationNode 
{
  // Add parts of NavigationNode that you want to publish
}

public class NavigationModel
{
    public List<INavigationNode> NavigationNodes { get; set; }
    public NavigationModel()
    {

    }

    private class NavigationNode : INavigationNode
    {

    }
}

NavigationNode needs to be public for this to work properly. Making it public still keeps the declaration internal to the containing class NavigationModel yet classes outside NavigationModel can reference it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM