How can I code a C# function to accept a variable number of parameters?

前端 未结 4 1023
谎友^
谎友^ 2021-01-23 11:21

I have a C# method that I would like to use to update some data. The method could be passed either a string, a double, an integer

public void Update(string ac, s         


        
4条回答
  •  梦毁少年i
    2021-01-23 11:55

    First of all, it seems you should pass all of these values in once, in a single custom class rather than making three separate calls. But if that's not what you want to or can do...

    If your various values can all be converted into strings before the function call, you can pass them in that way. In fact, if they are coming from textboxes, they may already be strings to start with. If your third parameter (e.g. "location", "beds") can definitively indicate the data type you want back, this should work, or you could pass the desired datatype in as well.

    If you need to pass in an integer value intVal:

    string strVal = intVal.ToString();
    Update(ac, pr, fld, strVal);
    

    Then inside your function, you will need to determine if the value you want to insert should be anything other than a string and convert it. I would recommend using Double.TryParse and Int32.TryParse to better trap errors.

    Last time...this is far from elegant but it can work and you indicated you might want to try it, so good luck and let me know if you run into any problems with this.

提交回复
热议问题