如何使课堂分班?

时间:2014-05-04 21:50:02

标签: c# partial-classes

在这些类中,我可以使类 ListBox 成为一个分类吗?如果有,可以有人给我看一些例子。如果不是,你能简单解释一下原因吗?

namespace example 
{
    public class Control
    {
        private int top;
        private int left;
        public Control(int Top, int Left)
        {
            top = Top;
            left = Left;
        }
        public void DrawControl()
        {
            Console.WriteLine("Drawing Control at {0}, {1}", top, left);
        }
    }

    // how to make this class ListBox a partial class?
    public class ListBox: Control
    {
        private string mListBoxContents;
        public ListBox(int top, int left, string theContent): base(top,left)
        {
            mListBoxContents = theContent;
        }
        public new void DrawControl()
        {
            base.DrawControl();
            Console.WriteLine("Writing string to the ListBox: {0}", mListBoxContents);
        }
    }

    public class Tester
    {
        public static void Main()
        {
            Control myControl = new Control (5,10);
            myControl.DrawControl();
            ListBox lb = new ListBox (20, 30, "Hello World");
            lb.DrawControl();
        }
    }
}

2 个答案:

答案 0 :(得分:2)

当然可以。您可以将所需的任何类声明为部分。没有任何情况你不能。只需使用以下声明

public partial class ListBox: Control
{

}

但是,我没有看到您想要创建此类partial的原因。通常,当我们想要在两个或多个源文件中拆分类的定义并使代码更易读和可维护时,我们使用partial类。有关进一步的文档,请查看here

答案 1 :(得分:0)

我不确定你的意图是什么,但它很简单:

public partial class ListBox: Control
{ }

使用可能会破坏代码的设计器时,部分类很有用。这不适用于不同的程序集。在某些情况下,抽象类更合适。

相关问题