gpt4 book ai didi

c# - 我执行 : c# extension methods 有什么问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:49:10 25 4
gpt4 key购买 nike

来源抛出错误:

'nn.asdf' does not contain a definition for 'extension_testmethod'

我真的不明白为什么...

using System.Linq;
using System.Text;
using System;

namespace nn
{
public class asdf
{
public void testmethod()
{
}
}
}
namespace nn_extension
{
using nn;
//Extension methods must be defined in a static class
public static class asdf_extension
{
// This is the extension method.
public static void extension_testmethod(this asdf str)
{
}
}
}
namespace Extension_Methods_Simple
{
//Import the extension method namespace.
using nn;
using nn_extension;
class Program
{
static void Main(string[] args)
{
asdf.extension_testmethod();
}
}
}

有什么想法吗?

最佳答案

扩展方法是一种静态方法,其行为类似于被扩展类型的实例方法,也就是说,您可以在 asdf 类型的对象实例上调用它.您不能将其作为扩展 类型的静态方法来调用。

更改您的 Main到:

asdf a = new asdf();
a.extension_testmethod();

当然,你总是可以像一个简单的调用,static声明类型的非扩展方法(asdf_extension):

asdf_extension.extension_testmethod(null);

关于c# - 我执行 : c# extension methods 有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1653999/

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