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/