开发者

abstract classes in C#

I want to create an abstract class in C#. Currently, I have this class in C#:

public class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string Em开发者_C百科ployerAddress { get; set; }
}

I want to make it abstract class and two other classes will inherit it. Do I just need to place abstract keyword with class to need to change properties as well. What about classes which will inherit this class. What need to be changed in these classes?

Please suggest.


All you need to do is mark the class as abstract:

public abstract class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string EmployerAddress { get; set; }
}


The only thing needed to make the class abstract is to add the keyword:

public abstract class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string EmployerAddress { get; set; }
}

In this case, implementing classes do not need to add any additional implementation:

class Derived : CreditReportViewModel { }

If you want to make members abstract as well, same thing goes there:

public abstract class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string EmployerAddress { get; set; }
    public abstract float MakeSomeCalculation();
}

public class Derived : CreditReportViewModel
{
    public override float MakeSomeCalculation()
    {
         // This method must be implemented in the derived class
    }
}

The typical case is that the abstract base class exposes some abstract members that need to be implemented by derived classes.


That depends on what you want the class to be. Usually it is enough to place the abstract keyword on the class level. If you want to have abstract properties, you have to mark them abstract as well.

Derived classes don't need any change as long as you mark the only the class as abstract. With abstract properties you force the derived classes to implement these properties.


yes, you need to place abstract keyword like

public abstract class CreditReportViewModel
{
    public Person Person { get; set; }       
    public DateTime ReportDate { get; set; }
    public string PersonalAddress { get; set; }
    public string EmployerAddress { get; set; }
}

but I don't think any valid reason you should make the above class abstract.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜