使用.NET 2.0的扩展方法?方法、NET

2023-09-02 10:26:11 作者:你是我的贵重物品

我想这样做,但得到这个错误:

1时出错无法定义一个新的扩展方法,因为所需的编译器类型System.Runtime.CompilerServices.ExtensionAttribute'无法找到。是否缺少引用System.Core.dll的? [剪断了一些路径的东西]

我已经看到了一些答案在这里,说,你必须定义这个属性吧。

我该怎么办呢?

编辑:这是我有:

  [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)
公共密封类ExtensionAttribute:属性
{
公共静态INT MeasureDisplayStringWidth(此Graphics图形,文本字符串)
{

}
}
 

解决方案

像这样:

  //你需要这个曾经头(只),并且必须是在这个命名空间
命名空间System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
         | AttributeTargets.Method)]
    公共密封类ExtensionAttribute:属性{}
}
//只要你喜欢,你可以有很多的这些,在任何命名空间
公共静态类MyExtensionMethods {
    公共静态INT MeasureDisplayStringWidth(
            该显卡的图形,文本字符串)
    {
           / * ... * /
    }
}
 

另外,只需添加一个参考 LINQBridge 。

NET2.0无法安装

I want to do this, but getting this error:

Error 1 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? [snipped some path stuff]

I have seen some answers here that says, you have to define this attribute yourself.

How do I do that?

EDIT: This is what I have:

[AttributeUsage ( AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method )]
public sealed class ExtensionAttribute : Attribute
{
	public static int MeasureDisplayStringWidth ( this Graphics graphics, string text )
	{

	}
}

解决方案

Like so:

// you need this once (only), and it must be in this namespace
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
         | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute {}
}
// you can have as many of these as you like, in any namespaces
public static class MyExtensionMethods {
    public static int MeasureDisplayStringWidth (
            this Graphics graphics, string text )
    {
           /* ... */
    }
}

Alternatively; just add a reference to LINQBridge.