简体   繁体   中英

Why can't I access class variables in function in Powershell 5?

I'm trying to define a class in Powershell v5 and I can't access variables from within class functions.

Ex.

PS C:\> class Foo{
          $bar = 'foobar'
          mymethod(){
            $bar + '123'
          }
        }
PS C:\> [Foo]::new().mymethod()
PS C:\> At line:4 char:11
        +           $bar + '123'
        Variable is not assigned in the method.

Use $this to access your variable:

class Foo{
      $bar = 'foobar'
      [string] mymethod(){
        return $this.bar + '123'
      }
    }

Output:

foobar123

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM