简体   繁体   中英

Assign variable values inside method

I'm trying to get make method in which I can assign values to multiple variables. I don't know how many variables I will have, but I know their type. The variables can all be of different types though.

I have googled quite a bit about this, and am fairly sure that this can't be done with managed code. (Correct me if I'm wrong though)

I don't know much (read: anything) about unsafe code. Can it be done that way? Maybe pass in an array of pointers to the variables I want to initialise and do it that way?

I am basically looking for a way to pass an arbitrary number of mixed type variables to a method and assign their values inside the method... Is it pie in the sky?

EDIT 1:

Here is some code which I hope illustrates what I would like to achieve:

private void SomeMethod()
{
    string a = string.empty;
    int b = 0;
    double c = 0;

    object[] testObject = new object[] { b, c };

    SetVariables(ref testObject);
}

public static void SetVariables(ref object[] Variables)
{
    for (int i = 0; i < Variables.Length; i++)
        Variables[i] = // The value the variable needs to have
}

After SetVariables has executed, a, b and c would be say:

a = "Some text"
b = 123
c = 1564.653

I am looking for a way to access the variables passed in as the parameter to SetVariables and modify their value. I guess that would mean accessing their storage location in memory, hence my thinking that I might need pointers?

EDIT 2:

My question here should give a better indication of the context in which I am trying to do this.

I will only be dealing with basic types: string, int, double and bool for the variables I want to assign to.

The data I am assigning from is in text format and has a variable number of fields. Each field should map to one of the input variable in the order in which the variables are passed in. If the order does not match there will be a misasignment at best or a type error at worst, but it is up to the user to make sure that the variables match the data.

What you are trying to do doesn't work well in C#. It is really a language thing, not a "managed vs un-managed" thing.

It usually doesn't come up that much, because in your sample code, you do know that you have 2 variables. You had to type them to enter them into the array.

If SetVariables() is going to be called from a lot of places in the code with different numbers of parameters, you could make a bunch of overloads of the method (with 1 parameter, 2 parameters, 3 parameters, etc).

But really to be honest, typically when you run into this case it is because you are doing something in an un-wise way.

Thinking more about it, how would the line:

Variables[i] = // The value the variable needs to have

would be expected to work in this scenario. How does it know what to set an arbitrary variable to, since it can be of any type? Also, what stops it from messing up the variable assignments if I change the call from passing in variable b, c to reversing them c, b ?

Logically, it starts to fall apart.

I guess what I'm trying to say is that C# doesn't support that very well, but it typically doesn't need to, because it rarely makes sense.


Trying to think of a working solution anyway; I would just have SetVariables just return the values, but not take in the parameters. It should be the other function's job to assign its variables. If you need to know the types, then just pass the types:

public object[] GetValues(params Type types)
{
    var result = new object[types.length];
    for (int i = 0; i < types.length; i++)
    {
        if(types[i] == typeof(string))
            result[i] = "foo";
        if(types[i] == typeof(int))
            result[i] = -1;
    }
    return result;
}

public void DoStuff()
{
    var data = GetValues(typeof(string), typeof(int), typeof(string));
    string foo1 = (string)data[0];
    int someNumber = (int)data[1];
    string foo2 = (string)data[2];
}

Its ugly, but it works...

Here is an example adapted from this answer to a similar question , unfortunately your problem is a little difficult to solve and there really isn't a simple way to accomplish what you want.

private static void SomeMethod() {
    string a = string.Empty;
    int b = 0;
    double c = 0;

    SetVariables(x => a = (string)x
               , x => b = (int)x
               , x => c = (double)x);

    Console.WriteLine("a: {0}\nb: {1}\nc: {2}", a, b, c);
}

public static void SetVariables(params Action<object>[] setters) {
    var tokens = new object[] { "Hello", 10, 14.235 };
    for (int i = 0; i < setters.Length; i++)
        setters[i](tokens[i]); // Assumed this is read and initialized properly
}

I'll admit this has a bit of a smell to it, but since you really have to account for a variable input it should get you closer to what you want without adding an excessive amount of complexity.

I think you are pretty close to the answer yourself. Assuming that the value assigned to the variable is only based off what type it is then assuming you use the code you posted above you can compare the value type with a typeof() check during your for loop:

if(Variables[i].GetType() == typeof(int)){
    //...do stuff
}

//etc...until you have an if for each data type you expect you might find

here is a link to the typeof documentation

I'm assuming you have looked at how to use reference types but just in case look here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM