我的实现有什么问题:c# 扩展方法
来源抛出错误:
'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();
}
}
}
有什么想法吗?
the source is throwing the error:
'nn.asdf' does not contain a definition for 'extension_testmethod'
and i really don't unterstand why...
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();
}
}
}
any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
扩展方法是一种静态方法,其行为类似于所扩展类型的实例方法,也就是说,您可以在
asdf
类型的对象实例上调用它。您不能将其视为扩展类型的静态方法来调用。将您的
Main
更改为:当然,您始终可以像调用声明类型的简单、
静态
、非扩展方法(>asdf_extension
):An extension method is a static method that behaves like an instance method for the type being extended, that is, you can call it on an instance of an object of type
asdf
. You can't call it as if it were a static method of the extended type.Change your
Main
to:Of course, you can always call like a simple,
static
, non-extension method of the declaring type (asdf_extension
):扩展方法适用于类实例:
Extension methods apply to class instances: