C#中的抽象基类(Abstract Base Class)和接口(Interface)

抽象基类和接口有很多类似的地方,那么我们在软件架构的过程中如何决定该用抽象基类还是接口呢?Stack Overfollow上有一个回答总结得比较好,虽然只有短短几十个字:

Abstract classes and interfaces are semantically different, although their usage can overlap.

An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.

An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.

可以这么理解:基类是爹,接口是能力。爹只能有一个,而且他决定了你是什么,但能力可以有多个。

应该考虑使用抽象基类的场景:

  • 逻辑上是同一类的东西(is a...);
  • 有需要实现的公共方法或属性;
  • 需要序列化的成员类型(因为接口无法序列化);

阅读:143

Unity的C#编译器的一个BUG:Object Initializer错误

假设有如下代码:

using System;
 
class A
{
 public int i = 1;
 public int j = 2;
}
public class Program
{ 
 public static void Main()
 {
 A a = new A {i = 0, j = 0};
 Console.WriteLine("a.i = {0}, a.j = {1}", a.i, a.j);
 }
}


继续阅读Unity的C#编译器的一个BUG:Object Initializer错误

阅读:19