Is There a Syntax Shortcut for Multiple Initialization in C#?

坚强是说给别人听的谎言 提交于 2019-12-23 10:06:37

问题


Is there a way to do this:

valueType x = 1, y = 1, z = 1;

with less characters?
e.g. When I have a large amount of state to initialize to the same starting value.
Thanks!


回答1:


If the starting value is zero and they are members of your class (not local variables) then you don't need to explicitly initialize them to zero.

Otherwise, no.

Would it make sense to use arrays instead of having a large number of parameters?




回答2:


You could try

int x, y, z;
x = y = z = 1;

But I can't see how it would help you... if you have really lots of variables you must initialize to the same thing, you could consider using some kind of collection:

var myInts = new List<int>();
for (int i = 0; i < 1000; i++)
    myInts.Add(1);



回答3:


in general I think it tends to be better to separate each declaration. It tends to make it easier to change around later.

especially when lots of variables tend to suggest that they should be combined into another object.

so I'd tend to do...

valueType  x = IntialValue;
valueType  y = IntialValue;
valueType  z = IntialValue;

etc...




回答4:


Lets say all your "variables" are actually fields of a POCO (plain old CLR object, that is, and object that serves no purpose but to hold data).

class State {
    public double pression_top;
    public double pression_bottom;
    /* hundreds and hundres of fields */
}

In that case, you could do something like:

var myState = new State();
var t = typeof(State);
foreach (var field in t.GetFields()) {
    field.SetValue(myState, 1);
}

Note however that this code is not optimized, and not very concurrency-friendly.



来源:https://stackoverflow.com/questions/2068421/is-there-a-syntax-shortcut-for-multiple-initialization-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!