通过接口扩展功能

本文关键字:功能 扩展 接口 | 更新日期: 2023-09-27 17:57:06

我实现了一个接口IService,它继承了一系列其他接口的功能,并作为许多不同服务的共同基础。

这些服务中的每一个都由一个接口描述,例如:

public interface IServiceOne : IService 
{
  //...
}
public class ServiceOne : IServiceOne
{
  //...
}

到目前为止,一切都按预期工作:

IServiceOne serviceOne = new ServiceOne();
IServiceTwo serviceTwo = new ServiceTwo(); 

我现在要做的就是向这些服务中添加一大列表的常量(公共变量),但是这些常量根据服务类型会有所不同(例如,IServiceOne的常量与IServiceTwo不同,IServiceOne中将有常量在IServiceTwo中不存在,等等)。

我想要实现的是这样的:

IServiceOne serviceOne = new ServiceOne();
var someConstantValue = serviceOne.Const.SomeConstant;

仅仅因为变量会因服务类型而异,我决定为每个变量实现一个额外的接口:

public interface IServiceOneConstants
{
   //...
}

然后扩大我的IService定义:

public interface IServiceOne : IService, IServiceOneConstants 
{
  //...
}
public class ServiceOne : IServiceOne
{
  //...
}

我现在遇到的问题是我不知道如何实现IServiceOneConstants的具体类。显然,当它的一个变量(我们在这里称它们为常量)被调用时,它必须被实例化,所以最初我虽然是一个static类,但随后你不能通过接口公开static类的功能。然后,我尝试使用singleton来执行此操作,并通过公共非静态包装器公开其instance

public class Singleton : IServiceOneConstants
{
    private static Singleton _instance;
    private Singleton()
    {
        SomeConstant = "Some value";
    }
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
    public String SomeConstant { get; set; }
    public Singleton Const
    {
        get
        {
            return Instance;
        }
    }
}

然后我像这样调整IServiceOneConstants

public interface IServiceOneConstants
{
   Singleton Const { get; }
}

但是当我称之为:

IServiceOne serviceOne = new ServiceOne();
var someConstantValue = serviceOne.Const.SomeConstant;

我得到一个null reference异常,因为.Const为空。

我在这里错过了什么?

通过接口扩展功能

你真的尽可能地帮助自己感到困惑,通过将不同的东西命名为同名;)

所以,首先...您尝试做的是通过实例属性访问单一实例:

public Singleton Const
    {
        get
        {
            return Instance;
        }
    }

然后你像这样使用它:

serviceOne.Const

但该变量从未被分配。为了分配它,你应该创建一个Singleton类的实例,将其分配给serviceOne.Const属性,然后你可以使用它。

你需要的可能是这样的:

public class ServiceOne : IServiceOne
{
   public Singleton Const
   { 
      get
      {
         return Singleton.Instance;
      }
   }
}

您需要检查单例是否已在 ServiceOne.Const.SomeConstant 的 getter 中实例化。 如果不是,则需要实例化它。 然后返回常量的值。