开发者

Is there a way to do C# 4.0 optional parameters in 2.0?

I have a method what accepts two parameters and now I need to pass along an additional parameter but all other code that calls this might not be passing that 3rd parameter along. below is an ugly hack but I'm just not familiar with the process of overloading and we are stuck in .NET 2.0 so while this works I can't help but feel its WRONG.

   public static void AddPlanFunds(ParticipantResultsPlan planNode, Plan plan)
    {
        AddPlanFunds(planNode, plan, -1);
    }
    public static void AddPlanFunds(ParticipantResultsPlan planNode, Plan plan, int participantId)
    {
        planNode.PlanFunds = new CommonPlanFunds();

        // Add single class funds
        AddSingleClassFunds(planNode.PlanFunds, plan);

        // Add portfolios
        AddPortfolios(planNode.PlanFunds, plan,participantId);
    }

how should I do the 开发者_如何学Pythonoverload?

thanks!


Your code is the standard way to do this; it isn't an ugly hack.

However, you should consider taking an int? and passing null rather than -1.

You can create optional parameters in C# 2 to be called from C# 4, using attributes.


Method overloading is not WRONG. That's exactly the way to do it in previous versions of the framework that don't support optional parameters.


Try to stay away from optional parameters, they are NOT automatic overloads, instead when compiling what happens is that the specified default values are taken and inserted into the calls automatically.

Why is this bad? Imagine if you change the default values and compile your solution, but a depending solution does not get recompiled and would therefore have the old default values. Optional parameters have their uses, but more in the area of COM programming.


That is how overloading works.

There are better ways to do it... but for your simple case it doesnt look bad.


Honestly I see nothing wrong with this approach. I know that in an environment without optional parameters, its use is rather ubiquitous.


That's exactly how I handle it in anything C# prior to 4.0. You COULD try the params int[] participantIds route, but then you'd have to be able to accept multiple in case someone provides more than one int.


This is 4.0, you may add optional parameters like ( for 2.0, the way you have mentioned is the right way)

public static void AddPlanFunds(ParticipantResultsPlan planNode, Plan plan, [Optional] int participantId) 
{
..
}

or can specify default value

public static void AddPlanFunds(ParticipantResultsPlan planNode, Plan plan,  int participantId = -1) 
{
..
}

you can call the method with either 2 parameters or 3 parameters

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜