我实现了一个接口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是空的。
我在这里错过了什么?
发布于 2014-04-07 11:58:55
你真的帮助自己尽可能地弄糊涂了,把不同的东西命名为同一个名字;)
所以首先..。您要做的是通过实例属性访问单例实例:
public Singleton Const
{
get
{
return Instance;
}
}然后你使用它就像:
serviceOne.Const但那个变量从来没有被分配过。为了分配它,您应该创建一个Singleton类的实例,将它赋值给serviceOne.Const属性,然后您可以使用它。
你需要的可能是这样的东西:
public class ServiceOne : IServiceOne
{
public Singleton Const
{
get
{
return Singleton.Instance;
}
}
}发布于 2014-04-07 00:21:00
您需要检查单例是否已在ServiceOne.Const.SomeConstants` getter中实例化。如果不是,则需要实例化它。然后返回常量的值。
https://stackoverflow.com/questions/22901647
复制相似问题