实现相同属性的 C# 类

问题描述:

我有几个具有相同属性的类.

I have a couple classes that have the same properties.

例如

public class Decimalclass
{
   public string SqlColumnName {get;set;}
   public SqlDbType SqlColumnType {get;set;}
   public Decimalclass()
   {
      SqlColumnType = SqlDbType.Decimal;
   }
   //...
}

public class Textclass
{
  public string SqlColumnName {get;set;}
  public SqlDbType  SqlColumnType {get;set;}
  public Textclass()
   {
      SqlColumnType = SqlDbType.NVarChar;
   }
   //...
}

public class Intclass
{
  public string SqlColumnName {get;set;}
  public SqlDbType  SqlColumnType {get;set;}
  public Intclass()
   {
      SqlColumnType = SqlDbType.Int;
   }
   //...
}

如您所见,这些类共享相同的属性,我正在尝试了解接口和抽象类.

As you can see those classes share the same properties, I am trying to learn about interfaces and abstract classes.

  • 您将如何通过创建一个接口来组织这些类持有他们分享的东西?
  • 界面是最好的方式吗?
  • 我可以将这些类添加到接口类型列表中吗?这样我就可以访问属性而无需强制转换?
  • 为什么是接口,为什么是抽象类,它们有什么优点彼此重叠

我会这样做:

public abstract class BaseClass
{
  public string SqlColumnName {get;set;}
  public SqlDbType  SqlColumnType {get;set;}
}

public class Intclass : BaseClass
{
   public Intclass()
   {
      base.SqlColumnType = SqlDbType.Int;
   }
}

更新以更好地回答 OP 问题

接口指定了实现接口的对象必须遵循的契约.而抽象基类提供了一种方法来在所有继承自它的对象中自动实现接口.

The Interface specifies a contract that must be followed on the object implementing the interface. Whilst the abstract base class provides a method to implement the interface automatically in all objects that inherit from it.

    interface IBase
    {
         string SqlColumnName { get; set; }
         SqlDbType SqlColumnType { get; set; }
    }

    public abstract class BaseClass : IBase
    {
        public string SqlColumnName { get; set; }
        public SqlDbType SqlColumnType { get; set; }
    }

    public class Intclass : BaseClass
    {
        public Intclass()
        {
            base.SqlColumnType = SqlDbType.Int;
        }
    }

因此,在该示例中,接口 IBase 表示所有实现者都必须包含这两个属性才能满足合同.这在遵循控制反转 IoC 或依赖注入模式时尤其有用.这允许您在新对象上实现接口并保持任何以 IBase 作为参数的兼容性.抽象类实现接口,然后从基类继承的任何对象继承该接口.基本上通过使用抽象基类,您不必在子对象中专门实现每个属性.

So in that example the interface IBase says that all implementer must contain these two properties to meet the contract. This is useful especially when following an Inversion of Control IoC or Dependency Injection pattern. This allows you to implement the interface on new objects and maintain compatibility anything that takes an IBase as an argument. The abstract class implements the interface which is then inherited by any object that inherits from the base class. Basically by using the abstract base class you don't have to specifically implement each property in your child objects.