首页 > Web开发 > 详细

Using Extension Methods in .NET 2.0

时间:2021-07-12 15:21:53      阅读:22      评论:0      收藏:0      [点我收藏+]

I was working on a series of dialogs that required validation, and since there‘s a funky validation setup in place, I thought I might build up a nice extension library. Noting that ASP.NET validation is far beyond Windows Forms, I thought it might also be a good opportunity to use extension methods.

Sadly, extension methods aren‘t supported by the C# 2.0 compiler (which I was using, part of Visual Studio 2005), nor are they supported by the .NET Framework 2.0. So, I wouldn‘t get IntelliSense support, and it wouldn‘t build in VS 2005. But I was curious, and since 2008 supports targeting the 2.0 framework, I thought I‘d give it a shot.

So I cranked open 2008 and created a quick test project. Building out the method:

     public static class ExtensionMethods
     {
         public static void ValidateMe(this Form form)
         {
             form.ValidateChildren(ValidationConstraints.Enabled);
         }
     }

I get a compiler error:

error CS1110: Cannot define a new extension method because the compiler required type ‘System.Runtime.CompilerServices.ExtensionAttribute‘ cannot be found. Are you missing a reference to System.Core.dll?

So it appeared I would need to link to the 3.5 libraries... or would I?

     namespace System.Runtime.CompilerServices
     {
         [AttributeUsage(AttributeTargets.Method)]
         public sealed class ExtensionAttribute : Attribute
         {
             public ExtensionAttribute() { }
         }
     }

Lo and behold, it compiled correctly. Then it worked correctly!

http://geekswithblogs.net/robp/archive/2007/12/20/using-extension-methods-in-.net-2.0-with-visual-studio-2008.aspx

Using Extension Methods in .NET 2.0

原文:https://www.cnblogs.com/x2009/p/15001435.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!