gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:15:30 25 4
gpt4 key购买 nike

  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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com