gpt4 book ai didi

c# - 为什么这在 C# 中不合法?

转载 作者:行者123 更新时间:2023-11-30 13:26:03 25 4
gpt4 key购买 nike

这行不通

public class Foo {
private int X { get; }

public Foo(string s) {
int.TryParse(s, out X);
}
}

但这行得通:

public class Foo {
private int X { get; }

public Foo(string s) {
int x;
int.TryParse(s, out x);
X = x;
}
}

两者有什么区别,因为 out 参数不需要初始化。为什么该属性不能作为输出参数传递?

最佳答案

我假设这是 C# 6.0,因为你有一个 get-only 属性。

它不起作用,因为不能通过引用传递属性。在 C# 中采用 ref intout int 参数的函数类似于在 C++ 中采用 int& 的函数。

但是 int 属性只是某个地址处的 int。属性可以在 getset 中运行它想要运行的任何代码。并且语言不应将自动实现的属性视为特殊属性。

如果我编写如下代码会怎样?

public class Foo {
private int X {
get { return 0; }
set { }
}

public Foo(string s) {
int.TryParse(s, out X);
}
}

根本没有任何 int 的地址可以传递给 TryParse。代码是否允许的规则不允许查看 getset 实现。

请注意,这工作正常:

public class Foo {
private int X;

public Foo(string s) {
int.TryParse(s, out X);
}
}

关于c# - 为什么这在 C# 中不合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33745991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com