|
||
|
|
#1 (permalink) |
|
Lurker
Join Date: Nov 2003
Posts: 9
|
Not sure exactly how to word this, but what's the best method of passing parameters to a function in C#, when you don't know the number or type of parameters at compile time? Is this possible? The type includes class instances as well as integers, characters, floats etc.
Thanks |
|
|
|
|
|
#2 (permalink) | |
|
RunUO Forum Moderator
|
Quote:
__________________
I always try to help
![]() Sometimes, I don't know how.... ![]() My Web Page Forum Rules ------------------------------------------------------------- Extensive OWLTR System | Token System | World Teleporters ------------------------------------------------------------- |
|
|
|
|
|
|
#3 (permalink) |
|
Forum Expert
|
Code:
public void Something( params object[] args )
{
// do something with the args
}
Code:
Something("hey", 1, new object(), "oh");
__________________
Angels are falling the very last time, down they're burning in hate and decline, unfaithful and violent we're breaking the spell, we're god, we're scissor, in heaven and hell! |
|
|
|
|
|
#4 (permalink) |
|
Lurker
Join Date: Nov 2003
Posts: 9
|
Thank you arul but that wasnīt what i was trying to do
.What i was trying to do is to invoke methods wich you donīt know their signature, parameter types and number at runtime. In depth, i was trying to instantiate several classes invoking their constructors when they havenīt a default constructor.I used the reflection classes as daat99 said to get the constructors, their number of parameters and their types.Then i made an instance for every parameter type, wich i think itīs an ugly way to do it.Is there other cleaner way to do it?. Code:
ConstructorInfo ctrinfo = tipo.GetConstructors();
ParameterInfo[] parinfo = ctrinfo[0].GetParameters();
if (ctrinfo.Length > 1 && parinfo[0].ParameterType == typeof(Serial))
parinfo = ctrinfo[1].GetParameters();
object[] parametros = new object[parinfo.Length];
for (int k = 0; k < parametros.Length; k++)
parametros[k] = Activator.CreateInstance(parinfo[k].ParameterType);
if (ctrinfo.Length > 1 && parinfo[0].ParameterType == typeof(Serial))
item = ctrinfo[1].Invoke(parametros);
else
item = ctrinfo[0].Invoke(parametros);
|
|
|
|
|
|
#5 (permalink) |
|
Forum Expert
|
It isn't an ugly way, it's the only way. If the constructor needs certain parameters to be passed, it's so for a good reason.
Of course your code may fail on some types, but that is the price you pay for not taking care of them one by one.
__________________
Angels are falling the very last time, down they're burning in hate and decline, unfaithful and violent we're breaking the spell, we're god, we're scissor, in heaven and hell! |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|