c#嵌套类和可见性?
我试图获得与combobox相同的功能,如combobox1.Items.Add()//editor.Tags.Tags1() 像这样:c#嵌套类和可见性?,c#,class,combobox,nested,nested-class,C#,Class,Combobox,Nested,Nested Class,我试图获得与combobox相同的功能,如combobox1.Items.Add()//editor.Tags.Tags1() 像这样: class Main() { // The editor is passed into the editor class, that allows the editor class to update the editor. MyEditorClass editor = new MyEditorClass(editorBox); edi
class Main()
{
// The editor is passed into the editor class, that allows the editor class to update the editor.
MyEditorClass editor = new MyEditorClass(editorBox);
editor.Tags.InsertTag1();
// Now i don't want people to do this
// MyEditorClass.TagClass tags = new MyEditorClass.TagClass();
}
原因是tags类调用传递到MyEditorClass中的editorBox,如果您在没有该编辑器的情况下创建一个tags类,它将无法工作
我的MyEditorClass看起来像这样:
public class MyEditorClass
{
static RichTextBox editor;
public TagClass Tags;
public MyEditorClass(RichTextBox editorBox)
{
editor = editorBox;
Tags = new TagClass();
}
public class TagClass
{
public void InsertTag1()
{
editor.Text += "Test tag 1";
}
}
}
我试图使TagClass保持静态,但没有成功。组合框是如何构造的?由于您不能使用Combobox.Items,但如果您声明了Combobox.Items,则可以在您声明的Combobox.Items上使用它。使您的
标记为属性只读
,然后它只能在构造函数中初始化:
public readonly TagClass Tags;
以后不能更改标记中存储的对象引用,并且该代码:
MyEditorClass editor = new MyEditorClass(editorBox);
editor.Tags = new MyEditorClass.TagClass();
不会编译
或者,第二种可能,甚至更好—只为标记
属性公开公共getter,并将实例私有地保存在MyEditorClass
类中,如下面的示例所示
顺便说一下,它与嵌套类没有任何关系。在公共类中包含公共类是很奇怪的
编辑:
要使结构类似于ComboBox
,以便TagClass
可以访问编辑器,可以将编辑器实例传递给TagClass
内部构造函数。构造函数是内部的,不允许外部代码直接使用TagClass
public class MyEditorClass
{
private readonly RichTextBox editor;
private readonly TagClass tags;
public TagClass Tags
{
get
{
return tags;
}
}
public MyEditorClass(RichTextBox editorBox)
{
editor = editorBox;
tags = new TagClass(editorBox);
}
}
public class TagClass
{
private RichTextBox _editor;
internal TagClass(RichTextBox editor)
{
_editor = editor;
}
public void InsertTag1()
{
_editor.Text += "Test tag 1";
}
}
现在这将起作用:
MyEditorClass editor = new MyEditorClass(editorBox);
editor.Tags.InsertTag1();
在TagClass类中,添加MyEditorClass类型的成员,并在创建新的TagClass实例时分配该成员:
public class TagClass
{
private MyEditorClass editor = null;
public TagClass(MyEditorClass parent)
{
this.editor = parent;
}
public void InsertTag1()
{
editor.Text += "Test tag 1";
}
}
...
Tags = new TagClass(this);
问题是我不知道如何构建我的类来反映组合框结构。(标记类还必须具有对编辑器的访问权限)。我希望所有标记都位于名为tags的方法/属性中。这使得它更容易使用。正常的MyEditorClass还将包含诸如Save、Open、new等元素。因此,如果有更好的方法来构建它,请让我知道=)Oops。。页面打开时间过长,未看到编辑..:/