当我尝试将我的单例类加载到 PowerShell 中时,我遇到了一些麻烦。具体来说,当我尝试访问实例时出现以下错误:
You cannot call a method on a null-valued expression.
At C:\Users\*Omitted*\Documents\visual studio
2012\Projects\ClassLibrary1\ClassLibrary1\bin\Debug\test.ps1:5 char:1
+ $test = [ClassLibrary1.Class1]::Instance.Foo()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
当我运行这个示例脚本时:
$currentScriptDirectory = Get-Location
[System.IO.Directory]::SetCurrentDirectory($currentScriptDirectory.Path)
[Reflection.Assembly]::LoadFrom("ClassLibrary1.dll") | fl
[ClassLibrary1.Class1] | Get-Member -Static
$test = [ClassLibrary1.Class1]::Instance.Foo()
在这个简单的类上:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
private static Class1 instance = null;
private Class1()
{
}
public static Class1 Instance
{
get
{
if (null == instance)
{
instance = new Class1();
}
return instance;
}
}
public string Foo()
{
return "HI THERE";
}
}
}
关于如何在不改变单例类的情况下摆脱这个错误的任何想法?我继承了我正在使用的类并且不能改变它的架构。