C#内部类别特定于外部类的实例
有没有办法使 C# 内部类实例特定于外部类的实例。例如,有没有办法做类似的事情
public class Group
{
public class Generator
{
}
}
Group Group1=new Group()
Group Group2=new Group()
Group1.Generator Generator1=new Group1.Generator();
Group2.Generator Generator2=new Group2.Generator();
,让 Generator1 和 Generator2 具有不同的类型?
对于上下文,我正在尝试编写一个群论项目,其中生成器仅在其父组中有意义,并且我希望避免传递对父组的显式引用并进行检查以确保父对象相等。
Is there a way to make C# inner class instances specific to the instance of the outer class. For example, is there way to do something like
public class Group
{
public class Generator
{
}
}
Group Group1=new Group()
Group Group2=new Group()
Group1.Generator Generator1=new Group1.Generator();
Group2.Generator Generator2=new Group2.Generator();
and have Generator1 and Generator2 be of different types?
For context, I am trying to write a group theory project where generators only make sense in their parent group, and I was hoping to avoid passing around explicit references to parent groups and checks to ensure parent objects are equal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您混淆了实例和类型的概念。您可以拥有带有泛型或子类的不同类型的组,但这可能不是必需的。首先尝试看看是否可以使用单个组类型和单个生成器类型对域进行建模。
在该设计中,没有必要使用生成器的嵌套类型,例如,只需使用:
如果生成器是组下的嵌套类型,则它将有权访问组的私有成员。但是嵌套类型不会自动引用封闭类型的实例,因此您仍然必须在其构造函数中传递 Group 实例。
You are confusing the ideas of instances and types. You can have different Types of Groups with either Generics or Subclasses, but it may not be necessary. Try first to see if you can model the domain with a single Group type and a single Generator type.
And using a Nested Type for Generator is not necessary in that design, eg simply use:
If Generator were Nested Type under Group, then it would have access to the private members of Group. But Nested Types don't get an automatic reference to an instance of the enclosing type, so you still have to pass a Group instance in its constructor.
恐怕您无法根据需要使用内部类,因为它们是特定于类的,而不是特定于实例的。
如果我理解正确的话,您希望有一种机制来区分同一组的生成器。
我可能会提出以下方法来实现它:
Equals
方法,它将比较这些封装的值。如果您不想显式传递这些值,则可以在 Group 内创建一个工厂方法,在其中创建与该组相关的生成器并隐式传递特定于组的值。False
:I am afraid that you can not use inner classes as you want because they are class-specific, not instance-specific.
If I understand you right, you want to have a mechanism to distinguish generators from the same group among others.
I may propose the following ways to achieve it:
Equals
method for Generator, which will compare those encapsulated values. If you do not want to pass those values explicitly, you can create a factory method inside Group, where you will create Generators related to this group and pass a group-specific value implicitly.False
will be printed: