当我尝试将其加载到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";
}
}
}
有关如何在不改变单例类的情况下摆脱此错误的任何想法?我继承了我正在使用的课程,无法改变其架构。
答案 0 :(得分:0)
主要问题是你得到了静态和实例混淆。静态意味着它是类级别,例如实例。 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";
}
}
}
然而,这不是一个防弹单身模式。 Jon Skeet在这里做了一些好的。
以下是它的正确实现:
public sealed class Class1
{
private static readonly Lazy<Class1> lazy =
new Lazy<Class1>(() => new Class1());
public static Class1 Instance { get { return lazy.Value; } }
private Class1()
{
}
public string Foo()
{
return "HI THERE";
}
}