c# - 默认对象实现

标签 c# object default

我想为继承树中的所有类实现默认对象模式。我正在做如下所示。

 namespace test
{
    public class Record
    {
        public int ID { get; set; }
    }

    public class StudentRecord : Record
    {
        public string StudentID { get; set; }
    }

    public class DriverRecord : Record
    {
        public string DLNumber { get; set; }
    }

    public class client
    {
        public static void Main()
        {
            StudentRecord st = StudentRecord.Default;
            DriverRecord dr = DriverRecord.Default;
        }
    }
}

我希望默认属性或方法将所有类级属性初始化为其默认值,我不想为每个类重复实现。我只想写在 Record (base) class 上。您能就此提出一些建议吗?

最佳答案

您正在寻找的正是构造函数的用途。构造函数可以调用继承的基础构造函数,因此您只需在一个地方进行基础初始化。有时基本功能确实可以满足您的需求:)

public class Record
{
    public int ID { get; set; }
    public Record()
    {
        // ... do general initialisation here ...
    }
}

public class StudentRecord : Record
{
    public string StudentID { get; set; }
    public StudentRecord()
        : base()    // This calls the inherited Record constructor,
                    // so it does all the general initialisation
    {
        // ... do initialisations specific to StudentRecord here ...
    }
}

public class client
{
    public static void Main()
    {
        // This calls the constructor for StudentRecord, which
        // in turn calls the constructor for Record.
        StudentRecord st = new StudentRecord();
    }
}

关于c# - 默认对象实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5537999/

相关文章:

C# Newtonsoft反序列化JSON数组

Java - 如何在多个类中使用同一个对象

JavaScript:如何使用默认功能打开新窗口?

netbeans - 在 NetBeans 中如何更改默认 JDK?

c# - 从 Form2 中的类中获取属性的值,并且该值已在 C# 中的 Form1 中设置

c# - 按空格键时停止默认的自动完成行为

jquery - 使用 jQuery 嵌套无序列表的对象

java - 在 java 中调用 System.exit() 的确切目的是什么

python - 有没有办法改变 Python 的 open() 默认文本编码?

c# - 复制文件时服务器变慢