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

我的 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 ;

}

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


www说
浏览 164回答 2
2回答

缥缈止盈

我通常做的是分配一个默认值 null 然后检查它是否为 null 并将其分配给一个新对象。类似于下面。private LanDataEchangeWCF_Wrapper(    ILanDataEchangeWCFCallback callbackReciever = null,    bool cleanExistingConnection = true,    bool requirePingToKeepAlive = true,    int pingFrequency = 30000){    callbackReciever = callbackReciever ?? new LanCallBackDefaultHandler();    //Rest of constructor}

子衿沉夜

构造函数重载 ?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;    }}
打开App,查看更多内容
随时随地看视频慕课网APP