【发布时间】:2013-06-28 23:04:41
【问题描述】:
当我尝试将我的单例类加载到 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";
}
}
}
关于如何在不改变单例类的情况下摆脱这个错误的任何想法?我继承了我正在使用的类,无法更改它的架构。
【问题讨论】:
-
您的类不是单例,您的 Instance 属性应该是静态的,当您将其设为静态时,您仍然会缺乏线程安全性。阅读:csharpindepth.com/articles/general/singleton.aspx,了解有关在 C# 中实现单例的不同方法的信息。
-
正如我在对 alex 的评论中所说,实际类具有正确的静态标记,编辑后的示例代码也是如此。而且由于我没有这个类的所有权,所以我不能修改它。
-
它仍然不是线程安全的。
标签: c# powershell dll singleton