c# - 为什么 base 关键字不能用在静态方法中?

标签 c#

为什么我们不能在静态方法中使用base关键字来使用基类方法?

两者都在编译时可用。

class A
{ 
    public virtual void Func(int a=4){
        Console.WriteLine(" A Class: "+a);
    }
}

class B : A
{
    public new void Func(int a = 12)
    {
        Console.WriteLine(" B Class: "+ a);
    }
}

class C : B
{
    public static void Func()
    {
        base.Func();  // why not ????
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        B ob = new C();
        ob.Func();
        Console.ReadLine();
    }
}

最佳答案

因为base关键字指的是当前类实例的基类。但是您在静态方法中没有当前实例 - 它们是静态的而不是实例。

如果您在类 B 中将 Func() 方法设为静态,您将能够调用 B.Func()

关于c# - 为什么 base 关键字不能用在静态方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14195581/

相关文章:

c# - 停止 Autofac 模块注册已经注册的组件

c# - ASPNET MVC - 为什么 ModelState.IsValid false "The x field is required"当该字段确实有值时?

c# - 我可以在具有动态IP的C#中创建套接字服务器吗?

c# - 如何在 C# 中的每个窗体加载上调用一个函数?

c# - Large Binary (byte[]) 通过WCF传输文件

C# 获取和设置列表集合的属性

c# - MapControllerRoute ,值不能为 null

c# - 从代码设置绑定(bind)在 xamarin.forms 应用程序中不起作用

c# - 如何从属性获取构造函数命名参数

c# - CTP 4 不考虑基类属性