我正在尝试单例基类文章中的一些代码。但是当我编译时,它给了我那个错误信息。我确保项目的目标框架是完整的 4.0,而不是 4.0 客户端框架。代码有什么问题?
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Reflection;
namespace ConsoleApplication1
{
public abstract class SingletonBase<t> where T : class
{
/// <summary>
/// A protected constructor which is accessible only to the sub classes.
/// </summary>
protected SingletonBase() { }
/// <summary>
/// Gets the singleton instance of this class.
/// </summary>
public static T Instance
{
get { return SingletonFactory.Instance; }
}
/// <summary>
/// The singleton class factory to create the singleton instance.
/// </summary>
class SingletonFactory
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonFactory() { }
// Prevent the compiler from generating a default constructor.
SingletonFactory() { }
internal static readonly T Instance = GetInstance();
static T GetInstance()
{
var theType = typeof(T);
T inst;
try
{
inst = (T)theType
.InvokeMember(theType.Name,
BindingFlags.CreateInstance | BindingFlags.Instance
| BindingFlags.NonPublic,
null, null, null,
CultureInfo.InvariantCulture);
}
catch (MissingMethodException ex)
{
throw new TypeLoadException(string.Format(
CultureInfo.CurrentCulture,
"The type '{0}' must have a private constructor to " +
"be used in the Singleton pattern.", theType.FullName)
, ex);
}
return inst;
}
}
}
public sealed class SequenceGeneratorSingleton : SingletonBase<SequenceGeneratorSingleton>
{
// Must have a private constructor so no instance can be created externally.
SequenceGeneratorSingleton()
{
_number = 0;
}
private int _number;
public int GetSequenceNumber()
{
return _number++;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Sequence: " + SequenceGeneratorSingleton.Instance
.GetSequenceNumber().ToString()); // Print "Sequence: 0"
}
}
}