2012-04-20 42 views
1

我正在嘗試從singleton base class article獲取一些代碼。但是當我編譯時,它給了我那個錯誤信息。我確定該項目的目標框架是4.0,而不是4.0客戶端框架。代碼有什麼問題?無法找到類型或命名空間名稱'T'(您是否缺少使用指令或程序集引用?)

下面的代碼:

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" 

     } 
    } 
} 

回答

2

是它的t的情況下?它應該是T。無論如何,它需要在整個班級中保持一致,而大寫則是慣例。

+1

哦,我的!也許我需要休息一下。 – 2012-04-20 04:48:01

+1

或新的眼鏡。 – 2012-04-20 04:59:42

1
public abstract class SingletonBase<t> where T : class 

應該是:

public abstract class SingletonBase<T> where T : class 

C#是區分大小寫的,因此編譯器看到where T : class爲是指一個未知的泛型類型參數,因爲您在類型delcaration,SingletonBase<t>使用小寫噸。

相關問題