简体   繁体   中英

c# referencing my calculation instead of just taking its value when assigning a float

This is what I have:

        float f1 = 1;
        float f5 = 10;
        float fout = f1 * 2;
        while (f1 * 2 < f5)
        {
            f1++;
        }

The float "fout" has the value the simple calculation of "f1 * 2" In my project that calculation is more complicated and uses about 4 local variables. In the above example I have to type in the same calculation twice: "f1 * 2" which is what I'm trying to avoid.

I am aware I could do it using a function:

        float f1 = 1;
        float f5 = 10;
        float fout = calc(f1);
        while (calc(f1) < f5)
        {
            f1++;
        }

        FUNCTION:
        float calc(float inn)
        {
            return inn * 2;
        }

But that will also look quiet ugly since I'll have to pass 4 local variables to the function in my real project and will end up creating a large amount of small functions only used twice.

But can I do it like this?

        float f1 = 1;
        float f5 = 10;
        float fout = ref (f1 * 2);
        while (fout < f5)
        {
            f1++;
        }

Making "fout" referencing my calculation instead of just taking its value as it is assigned. If so what is the correct syntax?

EDIT: Thank you to: Spook and undermind. This is what I was looking for:

        float f1 = 1;
        float f5 = 10;
        Func<float> fout = () => f1 * 2;
        while (fout() < f5)
        {
            f1++;
        }

If I understand you correctly, you may simply use a lambda. Eh, the lack of subfunctions in C-style languages...

float f1 = 1;
float f5 = 10;
Func<float> fout = () => f1 * 2;
while (fout() < f5)
{
    f1++;
}

Alternatively (depending on your needs):

float f1 = 1;
float f5 = 10;
Func<float, float> fout = (param) => param * 2;
while (fout(f1) < f5)
{
    f1++;
}

All local variables are accessible automatically.

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