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

前端 未结 4 1069
谎友^
谎友^ 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条回答
  •  不要未来只要你来
    2021-01-23 11:41

    EDIT

    It looks like you want to pass in a property name, and a value. A little bit of reflection should make this easy:

    public void Update(string ac, string pr, string propertyName, object Value) {
        try {
            vm.Product = _product.Get(ac, pr);
            vm.Product.GetType().GetProperty(propertyName).SetValue(vm.Product, value, null);
            _product.AddOrUpdate(vm.Product);
        }
    }
    

    END EDIT

    A params array allow your method to accept a variable number of parameters

    public void Update(string ac, string pr, params object[] arguments)
    

    Which could be called with any of your examples above

    Update("key1", "key2", "location", "London");
    Update("key1" , "key2", "beds", 2);
    Update("key1" , "key2", "price", 123.45);
    

提交回复
热议问题