Abstract class pattern for C#
I think about 80% of the usefulness of OOP comes down to having abstract classes which (1) provide certain functionality to their inheriting classes, and (2) require certain functionality of their inheriting classes (the other 20% is mostly interfaces and contructors). This is one of the first code examples that I do for languages that I'm learning. Here it is in C#. It is quite simple but you have to know that you don't need all the "internal", "new", "virtual" keywords and that you DO need the "override" keyword for the method which override abstract methods (different than in PHP).
翻译:我认为大约80%的面向对象的实用性,可以归结为抽象类(1)提供的某些功能为其继承类,(2)需要继承类的某些功能 / 其继承类需要一定的功能(其余20%大多是接口和contructors的) 。这是第一个代码例子,我做我学习的语言之一。在这里,它是在C#。这是很简单的,但你要知道,你并不需要所有的“内部”,“新”,“虚拟”的关键字,你需要覆盖抽象方法(该方法的“覆盖”关键字中的不同PHP)的

using System;
namespace TestOverriding234
{
public class Program
{
static void Main(string[] args)
{
Customer customer = new Customer { Id = 1, FirstName = "Jim", LastName = "Smith" };
Contract contract = new Contract { Id = 2, Title = "First Contract", Description = "This is the first contract" };
customer.ShowSystemFields();
contract.ShowSystemFields();
Console.ReadLine();
}
}
public class Customer : Item
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override void Load()
{
throw new NotImplementedException();
}
}
public class Contract : Item
{
public string Title { get; set; }
public string Description { get; set; }
public override void Load()
{
throw new NotImplementedException();
}
}
public abstract class Item
{
public in
public void ShowSystemFields()
{
Console.WriteLine("This item is a {0} and has Id={1}", this.GetType().Name, this.Id);
}
public abstract void Load();
}
}
引自:http://www.tanguay.info/web/index.php?pg=codeExamples&id=203
浙公网安备 33010602011771号