gpt4 book ai didi

c# - c#嵌套类的使用和可访问性

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:49 24 4
gpt4 key购买 nike

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

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);
}
}

}

最佳答案

将内部类标记为 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);
}
}
}

关于c# - c#嵌套类的使用和可访问性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10411436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com