gpt4 book ai didi

c# - 为什么在从被扩展类的方法中调用扩展方法时必须显式指定 "this"?

转载 作者:太空狗 更新时间:2023-10-30 00:54:25 32 4
gpt4 key购买 nike

public class StoreController : Controller
{
public string Index()
{
// implicitly specified instance does not work
//return GetMemberName();

// must specify this explicitly
return this.GetMemberName();
}
}

public static class Utilities
{
public static string GetMemberName(this Controller caller,
[CallerMemberName] string memberName = "")
{
return caller.GetType().FullName + "." + memberName;
}
}

当从被扩展类的方法中调用扩展方法时,为什么我们必须显式指定 this

在我的心智模型中,我们通常可以省略 this,例如当我们初始化字段时。

最佳答案

从技术上讲,扩展方法不是附加到您的类的方法。

yourClass.ExtensionMethod()yourClass.ClassMethod() 不同。

基本上,您正在做的是获得一种方便的方法:

ExtensionMethod(YourClass yourClass) {
//do something
return yourClass;
}

这是我对扩展方法的理解。这是针对无法更改的类调用方法的便捷方式。所以,这就是为什么不能在没有 this. 的情况下调用它的原因。它不是类方法。

关于c# - 为什么在从被扩展类的方法中调用扩展方法时必须显式指定 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12928690/

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