【问题标题】:How to make a class partial class?如何使班级偏班?
【发布时间】:2014-05-04 21:50:01
【问题描述】:

在这些类型的类中,我可以将类 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();
        }
    }
}

【问题讨论】:

    标签: c# partial-classes


    【解决方案1】:

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

    public partial class ListBox: Control
    {
    
    }
    

    但是,我不明白你为什么要参加这个课程partial。通常,我们使用partial 类,当我们想将类的定义拆分为两个或多个源文件,并使代码更具可读性和可维护性时。如需更多文档,请查看here

    【讨论】:

    • 使用部分类的一个原因是当你的类的部分代码是自动生成的。然后该工具对代码的更新不会删除您编写的代码。
    【解决方案2】:

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

    public partial class ListBox: Control
    { }
    

    Partials 类在使用可能会弄乱您的代码的设计器时很有用。这不适用于不同的程序集。对于某些情况,抽象类更合适。

    【讨论】:

    • 抱歉不清楚。由于 ListBox 继承自 Control 类,我是否必须在其他任何地方进行任何其他更改。
    • 没有。就我而言,不是。这样就完美了。
    猜你喜欢
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多