用扩展方法来为Enum类型加入业务逻辑

         我们在开发经常要使用Enum类型,今天我们用扩展方法来为Enum类型加入业务逻辑. 有以下的代码:

   1:      /// <summary>
   2:      /// StorageProviders
   3:      /// </summary>
   4:      [Serializable]
   5:      public enum StorageProviders
   6:      {
   7:          /// <summary>
   8:          /// LuceneIo
   9:          /// </summary>
  10:          LuceneIo = 0,
  11:          /// <summary>
  12:          /// LuceneVirtual
  13:          /// </summary>
  14:          LuceneVirtual = 1
  15:      }

          然后写一个扩展方法:

   1:    /// <summary>
   2:      /// StorageProvidersExtensions
   3:      /// </summary>
   4:      public static class StorageProvidersExtensions
   5:      {
   6:          /// <summary>
   7:          /// Determines whether the specified provider is virtual.
   8:          /// </summary>
   9:          /// <param name="provider">The provider.</param>
  10:          /// <returns>
  11:          ///     <c>true</c> if the specified provider is virtual; otherwise, <c>false</c>.
  12:          /// </returns>
  13:          public static bool IsVirtual(this StorageProviders provider)
  14:          {
  15:              return provider == StorageProviders.LuceneVirtual;
  16:          }
  17:      }

         好了,让我们来看如何使用:

   1:          [Test]
   2:          public void TestEnumExtesnsionMethod()
   3:          {
   4:              StorageProviders storageProviders = StorageProviders.LuceneVirtual;
   5:              Assert.IsTrue(storageProviders.IsVirtual());
   6:          }

         代码很简单,希望对您有开发有帮助。


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

你可能感兴趣的:(enum)