So, how do you use PowerShell to do .NET development?
Well, simple:
Add-Type @'
using System;
public class Sticks
{
// FIELDS
// CONSTRUCTORS
// PROPERTIES
// METHODS
}
'@
I entered this into my PowerShell IDE and hit "Run Script". This was the result:
WARNING: The generated type defines no public methods or properties.
Fair enough.
TIP: Add the following line to your profile:
set-alias new New-Object
Once I added this, I can do this:
PS Prompt> $test = new Sticks
PS Prompt> $test | get-member
TypeName: Sticks
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
As I understand, my new type is a .NET object added to this PowerShell session. The get-member cmdlet gives information about the public members of the class.
I added a property and a method from my first draft (which I am otherwise abandoning) to show how tests can be added. Here's a get-member on the revised class:
Name MemberType Definition
---- ---------- ----------
addStick Method bool addStick(int position) <--
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Value Property System.Int32 Value {get;} <-- And here's the test code that covers that: $test = new Sticks
if ($test.addStick(-1)) { "Broken: Accepted position value of -1."}
if ($test.addStick(12)) { "Broken: Accepted position value of 12."}
If it's working OK, the script will run without printing anything. The methods in my first run were bools. They return FALSE if they fail and MAKE NO CHANGES TO THE BOARD. A result of TRUE means they made the change expected (here, it means a stick was added.) (That approach is something I picked up doing C code.)
Here's the full script as it stands:
Add-Type @'
using System;
public class Sticks
{
// FIELDS
private bool[] board = new bool[12];
// CONSTRUCTORS
public Sticks()
{
}
// PROPERTIES
// adds up the number of matchsticks
public int Value
{
get
{
int temp = 0;
for (int i = 0; i <>
{
if (board[i]) temp++;
}
return temp;
}
}
// METHODS
public bool addStick(int position)
{
if (position <>
if (position > 11) return false;
if (board[position]) return true;
board[position] = true;
return true;
}
}
'@
$test = new Sticks
# value cannot be less than 0"Broken: Value cannot be less than 0."
if ($test.Value -lt 0) { "Broken: Value cannot be less than 0." }
#value cannot be greater than 11
if ($test.Value -gt 11) { "Broken: Value cannot be greater than 12."
}
if ($test.addStick(-1)) { "Broken: Accepted position value of -1."}
if ($test.addStick(12)) { "Broken: Accepted position value of 12."}
if ($test.Value -ne 0) {"Broken: Failed value assignment changed value."}
But I am throwing out this approach tomorrow. It got ugly really fast. I think a nested class will do what I want -- and cleanly, to boot.
No comments:
Post a Comment