构造函数具有默认值的Object参数?

时间:2018-06-12 14:20:41

标签: c#

My Singleton类有一个像这样的构造函数:

private LanDataEchangeWCF_Wrapper(
 // ILanDataEchangeWCFCallback callbackReciever ,// No error
    ILanDataEchangeWCFCallback callbackReciever = new LanCallBackDefaultHandler(), // Error
    bool cleanExistingConnection = true,
    bool requirePingToKeepAlive = true,
    int pingFrequency = 30000)
{
    if (cleanExistingConnection)
    {
        ExistingConnectionCleaner();
    }
    InitWs(callbackReciever);

    if (requirePingToKeepAlive)
    {
        timer = new Timer(pingFrequency);
        timer.Enabled = true;
        timer.Elapsed += KeepAlive;
    }
}

使用LanCallBackDefaultHandler接口ILanDataEchangeWCFCallback

的实现
class LanCallBackDefaultHandler : ILanDataEchangeWCFCallback
{
    public void WakeUP(int newID, string entity)
    {
        throw new NotImplementedException();
    }
}

我希望能够调用LanDataEchangeWCF_Wrapper()而不执行以下重载,这将是99%的代码重复:

private LanDataEchangeWCF_Wrapper(
    bool cleanExistingConnection = true,
    bool requirePingToKeepAlive = true,
    int pingFrequency = 30000)
{
    if (cleanExistingConnection)
    {
        ExistingConnectionCleaner();
    }
    InitWs(new LanCallBackDefaultHandler());

    if (requirePingToKeepAlive)
    {
        timer = new Timer(pingFrequency);
        timer.Enabled = true;
        timer.Elapsed += KeepAlive;
    }
}

当试图找出如何做到这一点时,我遇到的最后一个错误是

  

默认参数需要是编译时间常量

使用构造函数我不能做一些简单的函数重载,这将删除代码重复:

private object Methode() 
{
    return new Methode(new LanCallBackDefaultHandler());
}
private object Methode(ILanDataEchangeWCFCallback callbackReciever){
    //Do things
    return ;
}

如何获取对象的编译时常量新实例?

2 个答案:

答案 0 :(得分:1)

我通常做的是分配默认值null,然后检查它是否为null并将其分配给新对象。与下面类似。

private LanDataEchangeWCF_Wrapper(
    ILanDataEchangeWCFCallback callbackReciever = null,
    bool cleanExistingConnection = true,
    bool requirePingToKeepAlive = true,
    int pingFrequency = 30000)
{
    callbackReciever = callbackReciever ?? new LanCallBackDefaultHandler();


    //Rest of constructor
}

答案 1 :(得分:1)

构造函数重载?

private LanDataEchangeWCF_Wrapper(bool cleanExistingConnection = true, 
                                  bool requirePingToKeepAlive = true, 
                                  int pingFrequency = 30000)
: this (new LanCallBackDefaultHandler(), 
        cleanExistingConnection, 
        requirePingToKeepAlive, 
        pingFrequency) {}

private LanDataEchangeWCF_Wrapper(ILanDataEchangeWCFCallback callbackReciever,
                                  bool cleanExistingConnection = true,
                                  bool requirePingToKeepAlive = true,
                                  int pingFrequency = 30000)
{
    if (cleanExistingConnection)
    {
        ExistingConnectionCleaner();
    }
    InitWs(callbackReciever);

    if (requirePingToKeepAlive)
    {
        timer = new Timer(pingFrequency);
        timer.Enabled = true;
        timer.Elapsed += KeepAlive;
    }
}