簡體   English   中英

從方法訪問字段的正確方法是什么?

[英]What's the proper way to access fields from methods

我想從方法訪問類中的StringBuilder字段。 字段和方法都是非靜態的。 我已經嘗試了很多方法,無論我采用哪種方式,這一切似乎都有效,但我只是想知道正確的方法是什么。 這是我的意思的一個例子:

public class ExampleClass {
    private StringBuilder sb = new StringBuilder();
    private void call() {
        sb.append("Test"); // I can do it this way
        this.sb.append("Second way"); // or this way
        // does it matter? can someone explain it to me?
    }
    public static void main(String[] args) {
        ExampleClass ec = new ExampleClass();
        ec.call();
    }
}

我只是不明白這一點。 我可能只是一個完全白痴,但訪問該領域的正確方法是什么?

非常感謝,

保羅

這兩者之間存在差異

sb.append("Test"); // I can do it this way
this.sb.append("Second way"); // or this way

只有當你在上下文中有一些其他變量時,也稱為sb

例如:

public class ExampleClass {
    private StringBuilder sb = new StringBuilder();
    private void call(StringBuilder sb) {
        sb.append("Test"); //refers to the parameter passed to the function
        this.sb.append("Second way"); //refers to your member
    }
    public static void main(String[] args) {
        ExampleClass ec = new ExampleClass();
        StringBuilder sb = new StringBuilder();
        ec.call(sb);
    }
}

在您的示例中, sbthis.sb引用相同的對象,該對象是ExampleClass的該實例的ExampleClass 你可以使用它們中的任何一個。

在你的情況下,我只會使用sb因為沒有歧義。 在以下情況下使用this功能非常有用:

public void setBuilder(StringBuilder sb) {
    this.sb = sb;
}

this.sb是你的類字段, sbsetBuilder方法的參數。

沒有“正確的方法”來做到這一點。 我更喜歡不使用this除非它是模棱兩可的,因為在IDE中,該字段為我突出顯示,所以我可以看到它正在解析為一個字段。 此外,過多的this的混亂了代碼。 許多其他人更願意添加this因為這樣就不會給讀者帶來歧義。

我不確定這個案例是否有標准。

基本上“this”是隱含的,在你的情況下沒有歧義(如果你有一個具有相同名稱的參數,或者超類中的受保護/公共字段,則可能存在歧義)。

我通常使用“this”,但這是個人品味的問題,我發現當我訪問類參數時,更容易快速查看。

兩者本身都在做同樣的事情。 在這種情況下,使用這個是多余的..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM