out 的全部意义在于它保证(嗯,至少在 C# 级别……而不是 IL 级别)覆盖此值。这样做的目的是避免不必要的分配,同时允许“明确分配”。例如:
int i; // note: not assigned
var s = string.Empty;
// here "i" is not "definitely assigned"
int.TryParse(s, out i);
// here "i" is "definitely assigned"
想法是你使用返回值,例如:
if(int.TryParse(s, out i)) {
// here "i" makes sense; feel free to use it
} else {
// here you shouldn't use the value of "i"
}
在您的具体情况下,您可以重新订购:
if(!int.TryParse(s, out i)) i = int.MinValue;
特别要注意(至少在 C# 中)方法必须分配值,并且不能使用传入的值;例如:
static void Foo(out int i) {
return; // error: hasn't assigned to i
}
static void Bar(out int i) {
int j = i; // error: cannot read from "i" until Bar has assigned a value
i = j;
}
static void Baz(out int i) {
i = 0; // note that after this assignment, code in Baz can read from "i"
}
对比ref;当传递ref 值时,必须在调用者处明确分配。方法本身可能会或可能不会查看传入的值(根据它的选择),并且可能会或可能不会分配一个新值(根据它的选择)。例如:
int i;
SomeMethod(ref i); // illegal - "i" is not definitely assigned
int i = 0;
SomeMethod(ref i); // legal
和:
static void Foo(ref int i) {
return; // perfectly legal to not look at "i" and/or not assign "i"
}
static void Foo(ref int i) {
i = i + 1; // perfectly legal to look at "i" and/or assign "i"
}