- Powershell Core 6.2 Cookbook
- Jan Hendrik Peters
- 351字
- 2021-06-24 15:14:30
How to do it...
Perform the following steps:
- Open your favorite editor and examine the following C# code:
namespace Vehicle
{
public class Car
{
public string Make {get; set;}
public string Model {get; set;}
public ConsoleColor Color {get; set;}
public UInt16 TireCount {get;set;}
public UInt16 Speed {get; private set;}
public Car()
{
TireCount = 4;
}
public Car(string make, string model, ConsoleColor color)
{
Color = color;
Make = make;
Model = model;
}
}
}
- Notice the namespace keyword right at the beginning. Namespaces are collections of classes, enumerations, and other types. If you want to compare this to Java, think of a package:
namespace Vehicle
- There are usually one or more classes inside a namespace. Classes are templates for new objects that are created. Think of the Get-Process cmdlet – every time you execute this cmdlet, data is pulled from the operating system and figuratively molded by the template into an output you can then use:
public class Car
- Classes usually possess properties (or fields), methods, events, and more. Each new object that's created from this class, often called an instance of a class, automatically possesses every property, method, and so on that the class template has defined. Add the following properties to the body of your class inside curly braces:
public string Make {get; set;}
public string Model {get; set;}
public Nullable<ConsoleColor> Color {get; set;}
public UInt16 TireCount {get;set;}
public UInt16 Speed {get; private set;}
- Execute the following command:
$car = New-Object -TypeName Vehicle.Car
- Examine your new object by outputting it. At the moment, it looks pretty bare, apart from some default values:
$car
<# Will output:
Make :
Model :
Color :
TireCount : 4
Speed : 0
#>
- Classes usually contain a so-called constructor. The constructor in C# is automatically generated, but can be redefined to allow passing parameters, as you can see in the following example:
$car = New-Object -TypeName Vehicle.Car -ArgumentList 'Opel','GT','Red'
$car
<#
Make : Opel
Model : GT
Color : Red
TireCount : 4
Speed : 0
#>
- A shortcut to creating new objects is to execute the constructor directly with the static new method. To learn more about static methods, read through this chapter! Use the new method of the Vehicle.Car class to create a new car:
[Vehicle.Car]::new('Opel','GT','Red')