C# for loop with already defined iterator

2020-04-18 05:06发布

I want to make a loop using an already-defined iterator.

At present I am using

int i;
while (i<10)
{
    Console.Writeline(i);
    i++;
}

This is ugly because someone else might later remove the i++. If it is separated from the while statement by a large block of code, it will not be clear what it is for.

What I'd really like is something like

int i;
for (i<10; i++)
{
    Console.Writeline(i);
}

This makes it clear what's going on, but it's not valid C#.

The best I've come up with so far is

int i;
for (int z; i<10; i++)
{
    Console.Writeline(i);
}

But that's ugly. Does C# give me an elegant way of doing it?

标签: c#
3条回答
家丑人穷心不美
2楼-- · 2020-04-18 05:42

Well, you don't have to have anything inside the first part of the loop:

for (; i < 10; i++)
{
    Console.WriteLine(i);
}

Is that what you're looking for? Personally I would typically try to avoid this sort of situation anyway though - I find it pretty unusual to want a loop without a new variable.

查看更多
劳资没心,怎么记你
3楼-- · 2020-04-18 05:47

Just use an empty first part of the "for":

int i;
for (; i<10; i++)
{
    Console.Writeline(i);
}
查看更多
一夜七次
4楼-- · 2020-04-18 06:06

You can also assign the variable to itself in the first part of the loop like this:

int i;
for (i=i; i<10; i++)
{
    Console.Writeline(i);
}

I find that it's slightly clearer than leaving the first part of the loop blank, however Visual Studio will give you a warning "Assignment made to the same variable; did you mean to assign it to something else?"

查看更多
登录 后发表回答