开发者

defaultValue of parameter in C#

I have the following class of Schedule and using .Net Framework 4.0.

this class has two constructors, both having the parameter of interval with a default value of 120 seconds. is there any way to set the default value of interval in a private variable and then assign that variable to interval parameter. I tried doing it, but I get a compile time error saying Default parameter value for 'interval' must be a compile-time constant

public class Schedule
{
    public Delegate Callback { get; set; }
    public object[] Params { get; set; }
    public int Interval { get; set; }

    public Schedule(Delegate callback, int interval = 120)
    {

    }

    public Sched开发者_运维百科ule(Delegate callback, object[] parameters, int interval = 120)
    {

    }
}


No, because the way that optional parameters work is that the compiler of the calling code has the default value baked into it. So a call like this:

new Schedule(MyCallback)

is converted at compile-time into:

new Schedule(MyCallback, 120)

So that's why it has to be a constant. Now, you can still make that a constant - even a private one, if you want - but it can't be a normal variable. So this would be okay:

public class Schedule
{
    private const int DefaultInterval = 120;

    public Schedule(Delegate callback, int interval = DefaultInterval)
    {

    }

    public Schedule(Delegate callback, object[] parameters,
                    int interval = DefaultInterval)
    {
         ...
    }
}

If you want a value which may vary at execution time, you could use a nullable type as the parameter, with the null value being the default, replaced by the real default at execution time. For example, here's a method which allows you to specify a timestamp, but defaults to "now":

public void Foo(DateTime? timestamp = null)
{
    DateTime realTimestamp = timestamp ?? DateTime.UtcNow;
    ...
}


There's no way to have a dynamic value as default parameter. It should be known at compile time. In fact the it is the same set of values that can be used as default parameter as for attribute arguments because default parameters values are emitted as the DefaultParameterValueAttribute attribute.

You could use a constant:

private const int DefaultInterval = 120;
public Schedule(Delegate callback, int interval =DefaultInterval)
{

}

public Schedule(Delegate callback, object[] parameters, int interval = DefaultInterval)
{

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜