How can you use optional parameters in C#?

2019-01-01 05:17发布

Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).

We're building a web API that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b) and the API has a method GetFooBar taking query params like &a=foo &b=bar.

The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?

19条回答
爱死公子算了
2楼-- · 2019-01-01 05:24

A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,

[WebMethod]
public string Foo(string arg1, XmlNode optarg2)
{
    string arg2 = "";
    if (optarg2 != null)
    {
        arg2 = optarg2.Value;
    }
    ... etc
}

What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).

查看更多
伤终究还是伤i
3楼-- · 2019-01-01 05:25

Instead of default parameters, why not just construct a dictionary class from the querystring passed .. an implementation that is almost identical to the way asp.net forms work with querystrings.

i.e. Request.QueryString["a"]

This will decouple the leaf class from the factory / boilerplate code.


You also might want to check out Web Services with ASP.NET. Web services are a web api generated automatically via attributes on C# classes.

查看更多
柔情千种
4楼-- · 2019-01-01 05:27

From this site:

http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:

using System.Runtime.InteropServices;
public void Foo(int a, int b, [Optional] int c)
{
  ...
}

In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.

查看更多
琉璃瓶的回忆
5楼-- · 2019-01-01 05:28

optional parameters are for methods. if you need optional arguments for a class and you are:

  • using c# 4.0: use optional arguments in the constructor of the class, a solution i prefer, since it's closer to what is done with methods, so easier to remember. here's an example:

    class myClass
    {
        public myClass(int myInt = 1, string myString =
                               "wow, this is cool: i can have a default string")
        {
            // do something here if needed
        }
    }
    
  • using c# versions previous to c#4.0: you should use constructor chaining (using the :this keyword), where simpler constructors lead to a "master constructor". example:

    class myClass
    {
        public myClass()
        {
        // this is the default constructor
        }
    
        public myClass(int myInt)
            : this(myInt, "whatever")
        {
            // do something here if needed
        }
        public myClass(string myString)
            : this(0, myString)
        {
            // do something here if needed
        }
        public myClass(int myInt, string myString)
        {
            // do something here if needed - this is the master constructor
        }
    }
    
查看更多
余欢
6楼-- · 2019-01-01 05:29

Another option is to use the params keyword

public void DoSomething(params object[] theObjects)
{
  foreach(object o in theObjects)
  {
    // Something with the Objects…
  }
}

Called like...

DoSomething(this, that, theOther);
查看更多
爱死公子算了
7楼-- · 2019-01-01 05:30

You can use optional parameters in C# 4.0 without any worries. If we have a method like:

int MyMetod(int param1, int param2, int param3=10, int param4=20){....}

when you call the method, you can skip parameters like this:

int variab = MyMethod(param3:50; param1:10);

C# 4.0 implements a feature called "named parameters", you can actually pass parameters by their names, and of course you can pass parameters in whatever order you want :)

查看更多
登录 后发表回答