C# VS2008中.NET2.0的扩展方法
我在顶部添加了以下内容:C# VS2008中.NET2.0的扩展方法,c#,.net,C#,.net,我在顶部添加了以下内容: public static class Helper { public static float ToFloat(this string input) { float result; return float.TryParse(input, out result) ? result : 0; } } 但我仍然在Helper类中的“this”上得到了预期的错误类型。有什么问题吗 奇怪的是,针对.NET 2.0时
public static class Helper
{
public static float ToFloat(this string input)
{
float result;
return float.TryParse(input, out result) ? result : 0;
}
}
但我仍然在Helper类中的“this”上得到了预期的错误类型。有什么问题吗 奇怪的是,针对.NET 2.0时,以下编译和运行良好:
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method)]
public class ExtensionAttribute : Attribute
{
public ExtensionAttribute()
{
}
}
}
编辑:
它之所以能在命令行应用程序中工作,是因为msbuild知道2.0.NET CLR可以处理扩展方法(因为它们只是带有一些语法糖的静态方法)
编译项目时,msbuild会检查.csproj文件以了解如何编译、目标对象等
但在编译网站时,没有.csproj文件,因此msbuild无法检查如何编译。现在发生的事情是,命令行编译器csc启动时带有如何编译的参数。因此,在编译.NET2.0网站时,它会选择2.0编译器。但是2.0编译器不知道如何编译扩展方法,因此会出现错误
您还可以注意到,如果将常规项目的“高级”下的“生成选项”设置为使用ISO-2,它将警告您不能使用扩展方法。但是2.0编译器甚至不识别扩展方法,所以它只是告诉您不能使用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());
}
}
@James,要定义扩展方法,当然可以。事实上,你必须这样做。但不早于2.0.:)@James
这个
在他使用扩展方法的方式上是很正常的请看@Yuriy Faktorovich:我刚刚查看了我的扩展方法,你是对的。我删除了我愚蠢评论的证据,所以我不知道你们都在说什么:)我可以在一个新的控制台应用程序中这样做,但由于奇怪的原因,我不能在我的.net 2.0网站上这样做。我想我已经弄明白了为什么这在网站上不起作用。请检查我的答案
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string test = "0.0";
float f = test.ToFloat();
}
}
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()
{
}
}
}