readonly 和 { get; 之间有区别吗? }

发布于 2024-09-11 14:14:19 字数 82 浏览 6 评论 0原文

这些说法的意思是一样的吗?

int x { get; }
readonly int x;

Do these statements mean the same thing?

int x { get; }
readonly int x;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

美胚控场 2024-09-18 14:14:19

回答你的问题:readonly 和 {get; 之间有区别。 }:

在 int x { get; } (不会编译,因为无法设置 x - 我认为您需要 public int x { get; private set; } )您的代码可以不断更改 x

In readonly int x;,x 在构造函数或内联中​​初始化,然后永远不能更改。

In answer to your question: There is a difference between readonly and {get; }:

In int x { get; } (which won't compile as there's no way to set x - I think you needed public int x { get; private set; } ) your code can keep changing x

In readonly int x;, x is initialised either in a constructor or inline and then can never change.

浪推晚风 2024-09-18 14:14:19

readonly int x; 在类上声明一个只读字段。该字段只能在构造函数中分配,并且其值在类的生命周期内不能更改。

int x { 得到; } 声明了一个只读自动实现的属性,并且在这种形式下是无效的(因为您无法设置该值)。普通的只读属性不保证每次调用时返回相同的值。该值可以在类的整个生命周期中发生变化。例如:

public int RandomNumber
{
    get { return new Random().Next(100); }
}

每次调用都会返回不同的号码。 (是的,这是对财产的严重滥用)。

readonly int x; declares a readonly field on a class. This field can only be assigned in a constructor and it's value can't change for the lifetime of the class.

int x { get; } declares a readonly auto-implemented property and is, in this form, invalid (because you'd have no way whatsoever to set the value). A normal readonly property does not guarantee to return the same value every time it is called. The value can change throughout the lifetime of the class. For example:

public int RandomNumber
{
    get { return new Random().Next(100); }
}

This will return a different number everytime you call it. (Yes, this is a terrible abuse of properties).

流殇 2024-09-18 14:14:19

不,这些陈述并不意味着同一件事。属性的完整版本将有一个支持变量:

private int _x;

public int X
{
    get { return _x; }
}

类中的另一个方法可以修改支持变量,从而更改属性的值:

private void SomeMethod(int someValue)
{
    _x = someValue * 5;
}

readonly 关键字仅允许在其成员变量中分配成员变量。声明或构造函数中:

// Both of these compile

private readonly int _x = 1;

public SomeClass()
{
    _x = 5;
}

// This will not compile

private void SomeMethod(int someValue)
{
    _x = someValue * 5;
}

因此,其支持变量标记为 readonly 的仅 get 属性是真正的只读属性。

No, the statements do not mean the same thing. The full version of the property will have a backing variable:

private int _x;

public int X
{
    get { return _x; }
}

Another method in the class could modify the backing variable, changing the value of the property:

private void SomeMethod(int someValue)
{
    _x = someValue * 5;
}

The readonly keyword only allows a member variable to be assigned in its declaration or in the constructor:

// Both of these compile

private readonly int _x = 1;

public SomeClass()
{
    _x = 5;
}

// This will not compile

private void SomeMethod(int someValue)
{
    _x = someValue * 5;
}

So a get-only property whose backing variable is marked readonly is a true read-only property.

老街孤人 2024-09-18 14:14:19

其他答案有点过时了……

在较新版本的 C# 中,您可以为 int x { get; 分配默认值; } = 33; 这改变了事情。

基本上,它被编译为带有 readonly 私有支持字段的仅获取属性。 (有关更多详细信息,请参阅 https://softwareengineering.stackexchange.com/q/372462/81745

我的另一个区别看到的是,使用接口时不能使用只读版本,因为只能定义方法和属性。

Other answers are sorta outdated…

In newer versions of C# you can assign a default value to int x { get; } = 33; which changes things.

Basically, it gets compiled down to get-only property with a readonly private backing field. (See https://softwareengineering.stackexchange.com/q/372462/81745 for more details)

Another difference I see is that you can't use the readonly version when using interfaces as you can only define methods and properties.

若言繁花未落 2024-09-18 14:14:19

readonly 关键字确保这些变量一旦初始化就不会更改 // 它相当于将变量设为私有并为其设置 getter。
例子。

public class PlayerAuthData 
{
    public readonly string emailId, password, userName;
    private string hello;
    public PlayerAuthData(string emailId, string password, string userName)
    {
        this.emailId = emailId;
        this.password = password;
        this.userName = userName;
    }

    public string Hello 
    {
        get { return hello; }
        set { hello = value; }
    }
}

public class AuthManager
{
    void Start()
    {
        PlayerAuthData pad = new PlayerAuthData("[email protected]", "123123", "Mr.A");
        pad.Hello = "Hi there";
        print(pad.Hello);
        print(pad.password);
        print(pad.emailId);
        print(pad.userName);
    }
}

readonly keyword is making sure that these variables dont change once initialised // it is equalant to making a variable private and setting getter for it.
Example.

public class PlayerAuthData 
{
    public readonly string emailId, password, userName;
    private string hello;
    public PlayerAuthData(string emailId, string password, string userName)
    {
        this.emailId = emailId;
        this.password = password;
        this.userName = userName;
    }

    public string Hello 
    {
        get { return hello; }
        set { hello = value; }
    }
}

public class AuthManager
{
    void Start()
    {
        PlayerAuthData pad = new PlayerAuthData("[email protected]", "123123", "Mr.A");
        pad.Hello = "Hi there";
        print(pad.Hello);
        print(pad.password);
        print(pad.emailId);
        print(pad.userName);
    }
}
不气馁 2024-09-18 14:14:19

从字面上看,没有太大区别,因为您已将 x 声明为私有(默认)。您始终可以重新编译您的类以使 x 不同。

但是,如果它是公共的,则定义 public int x { get; } 允许您稍后将定义扩展为如下所示:

int x { get {
     return DoSomeOperation();
    }
}

您可以在不破坏客户端的情况下做到这一点。 getter 的实现是私有的,客户端在不知道它是静态值还是在其 get 访问器内有操作的情况下调用它。

Literally, there's no big difference because you've declared x to be private (the default). You can always re-compile your class to make x different.

However, if it were public, the definition public int x { get; } allows you to later expand the definition to something like this:

int x { get {
     return DoSomeOperation();
    }
}

You can do that without breaking your clients. The implementation of the getter is private and clients call it without knowing if it is a static value or has an operation inside its get accessor.

满天都是小星星 2024-09-18 14:14:19

属性可以具有可以使用该类的任何方法设置的支持变量,

private int a;
public int A{get;}

public void ChangeAMethod(int value){
    a=value;
}

但是只读字段只能在构造函数中或内联中分配。

Propery can have backing variable that can be set using any method of that class

private int a;
public int A{get;}

public void ChangeAMethod(int value){
    a=value;
}

However readonly fields can only be assigend in constructor or in-line.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文