I understand how to get the names of parameters passed to a method, but let's say I have a method declaration as follows:
static void ParamsTest(string template, params object[] objects)
and I want to use object/property names in my template for substitution with real property values in any of the objects in my `objects' parameter. Let's then say I call this method with:
ParamsTest("Congrats", customer, purchase);
I will only be able to retrieve two parameter names trying to fill out the template, viz, template
, and objects
, and the names of the objects in the objects
collection are forever lost, or not?
I could require a List<object>
as my second parameter, but I feel there is somehow a more elegant solution, maybe with a lambda or something. I don't know, I'm not used to using lambdas outside of LINQ.
Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
Parameters can be passed to a method in following three ways : Value Parameters. Reference Parameters. Output Parameters.
As you expect it, Python has also its own way of passing variable-length keyword arguments (or named arguments): this is achieved by using the **kwargs symbol. When using **kwargs, all the keywords arguments you pass to the function are packed inside a dictionary.
If you want the called method to change the value of the argument, you must pass it by reference, using the ref or out keyword. You may also use the in keyword to pass a value parameter by reference to avoid the copy while guaranteeing that the value will not be changed.
Inpsired by Mark I can offer an anonymous type answer :
using System;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
ParamsTest(new { A = "a", B = "b"});
}
public static void ParamsTest(object o)
{
if (o == null)
{
throw new ArgumentNullException();
}
var t = o.GetType();
var aValue = t.GetProperty("A").GetValue(o, null);
var bValue = t.GetProperty("B").GetValue(o, null);
}
}
}
However this DOES have drawbacks :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With