简体   繁体   English

如何使班级偏班?

[英]How to make a class partial class?

In these type of classes, can I make class ListBox a partial class? 在这些类型的类中,我可以使类ListBox成为部分类吗? If yes, can someone show me some example. 如果是,有人可以给我看一些例子。 If no, can you briefly explain why? 如果否,您能否简要解释原因?

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

Of course you can. 当然可以。 You can declare any class you want as partial. 您可以将任何想要的类声明为局部类。 There isn't any case in which you can't. 在任何情况下都无法做到。 Just use the following declaration 只需使用以下声明

public partial class ListBox: Control
{

}

However, I don't see the reason why you want to make this class partial . 不过,我不明白为什么要进行这个类的原因partial Usually, we use partial classes, when we want to split the definition of the class in two or more source files and make the code more readable and maintainable. 通常,当我们想将类的定义分为两个或更多的源文件并使代码更具可读性和可维护性时,我们使用partial类。 For further documentation, please look here . 有关更多文档,请参见此处

I am not sure what your intentions are but it as simple as this: 我不确定您的意图是什么,但它是如此简单:

public partial class ListBox: Control
{ }

Partials classes are useful when using a designer that could mess up your code. 在使用可能会使您的代码混乱的设计器时,Partials类非常有用。 This does not work across different assemblies. 这不适用于不同的程序集。 For some situations, abstract classes are more appropriate. 在某些情况下,抽象类更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM