Home > Net >  no object from a class with an empty class constructor
no object from a class with an empty class constructor

Time:09-13

I'm playing around with classes, I try to create an object from the class "testresult" and get an error: "Cannot find an overload for "new" and the argument count: "0". I understand the problem is in the first class "testitem", but quite why? There is a standard empty constructor in the class "testitem"?

# class definition
class TestItem
{
[bool]$TestResult
[string]$Message
# 1. constructor
TestItem([string]$Message, [bool]$TestResult)
{
    $this.Message = $Message
    $this.TestResult = $TestResult
}
# 2. standard constructor, empty
TestItem() {}
# ToString() overwrite
[string] ToString()
{
    return $this.Message
}
}
# the second class
class TestResult
{
[int]$TotalCount
[int]$PassedCount
[int]$FailedCount
[System.Collections.Generic.IList[TestItem]]$TestResult

# constructor
TestResult()
{
    $this.TestResult = [System.Collections.Generic.IList[TestItem]]::New()
    $this.FailedCount = 0
    $this.PassedCount = 0
    $this.TotalCount = 0
}
[void]Failed([string]$Message)
{
    $this.AddResult($Message,$false)
}
[void]Passed([string]$Message)
{
    $this.AddResult($Message,$true)
}

[void]AddResult([string]$Message, [bool]$Result)
{
    $testItem = [TestItem]::new($Message, $Result)
    $this.TotalCount  
    if($Result)
    {
        $this.PassedCount  
        Write-Verbose "[ ]Passed $Message" -Verbose
    }
    else {
        $this.FailedCount  
        Write-Verbose "[-]Failed $Message" -Verbose
    }
    $this.TestResult.Add($testItem)
}
}

$results = [TestResult]::new()
$results

CodePudding user response:

You're trying to create an instance of [IList[TestItem]] - but the I in IList stands for interface - an abstract kind of type which can't actually be instantiated.

You'll want to create a [List[TestTime]] - List implements all the members declared by the [IList[TestTime]] type, but is concrete, meaning that we can actually create objects based on it:

$this.TestResult = [System.Collections.Generic.List[TestItem]]::new()
  • Related