c# - VS2008中.net 2.0的扩展方法

标签 c# .net

  public static class Helper
  {
    public static float ToFloat(this string input)
    {
      float result;
      return float.TryParse(input, out result) ? result : 0;
    }
  }

我在顶部添加了以下内容:

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

        }
    }
}

但我仍然在 Helper 类的“this”上收到类型预期错误。有什么问题 ?

最佳答案

奇怪的是,以下代码在面向 .NET 2.0 时可以正常编译和运行:

using System;

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

        }
    }
}

public static class Helper
{
    public static float ToFloat(this string input)
    {
        float result;
        return float.TryParse(input, out result) ? result : 0;
    }
}

class Program
{
    static void Main()
    {
        string foo = "123";
        Console.WriteLine(foo.ToFloat());
    }
}

关于c# - VS2008中.net 2.0的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7236202/

相关文章:

c# - 跨多个应用程序池的 ASP.Net C# 共享 session

.net - "EnsureBindingRedirects"任务意外失败

.net - 405 : Method Not Allowed

c# - .NET Core 1.1 如何获取当前属性的名称

c# - DataGridView 单元格文本和单元格值

c# - asp.net core webapi frombody参数大小限制

c# - 你什么时候真正需要在 Web 框架上使用异步?

c# - 如何在 Webbrowser 控件中捕获 XMLHTTP 请求?

c# - .NET 最小化到托盘并最小化所需资源

c# - Asp.net MVC 的从右到左 GridView