1

我知道嵌套类。我如何设计我的嵌套类,使得在嵌套类的父类之外没有人能够访问像实例创建等这样的嵌套类,因为我希望子类是私有的。我想通过父类属性或方法公开我的子类属性,方法一切。请指导我为这种嵌套类编写代码。谢谢

public class Person
{
private string _firstName;
private string _lastName;
private DateTime _birthday;

//...

public class FirstNameComparer : IComparer<Person>
{
    public int Compare(Person x, Person y)
    {
        return x._firstName.CompareTo(y._lastName);
    }
}

}
4

3 回答 3

7

将内部类标记为,private而不是public.

public class Person
{
    private string _firstName;
    private string _lastName;
    private DateTime _birthday;

    private FirstNameComparer firstNameComparer = new FirstNameComparer();

    public int CompareFirstNames(Person x, Person y)
    {
       return firstNameComparer.Compare(x, y);
    }

    //...

    private class FirstNameComparer : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return x._firstName.CompareTo(y._lastName);
        }
    }
}
于 2012-05-02T09:56:48.157 回答
2

你可以制作嵌套类private。主类将负责创建嵌套类实例。

于 2012-05-02T09:57:56.433 回答
1

您可以对嵌套类使用私有访问器。如果你想公开它的一些属性,你可以像这样为主类创建新属性:

private FirstNameComparer _FirstNameComparer = new FirstNameComparer();
public int Compare(Person x, Person y)
    {
        return _FirstNameComparer.Compare(Person x, Person y); 
    }
于 2012-05-02T10:01:01.307 回答