MyClass equivalent in C#

前端 未结 3 1241
醉梦人生
醉梦人生 2021-02-18 22:33

In looking at this question, commenter @Jon Egerton mentioned that MyClass was a keyword in VB.Net. Having never used it, I went and found the document

相关标签:
3条回答
  • 2021-02-18 23:11

    There is no C# equivalent of the MyClass keyword in VB.Net. To guarantee that an overridden version of a method will not be called, simply make it non-virtual.

    0 讨论(0)
  • 2021-02-18 23:23

    According to Jon Skeet, there is no such equivalent:

    No, C# doesn't have an equivalent of VB.NET's MyClass keyword. If you want to guarantee not to call an overridden version of a method, you need to make it non-virtual in the first place.

    An obvious workaround would be this:

    public virtual void MyMethod()
    {
        MyLocalMethod();
    }
    
    private void MyLocalMethod()
    {
        ...
    }
    

    Then you could call MyLocalMethod() when a VB user would write MyClass.MyMethod().

    0 讨论(0)
  • 2021-02-18 23:34

    In addition to answers saying it doesn't exist, so you have to make it non-virtual.

    Here's a smelly (read: don't do this!) work-around. But seriously, re-think your design.

    Basically move any method that must have the base one called into 'super'-base class, which sits above your existing base class. In your existing class call base.Method() to always call the non-overridden one.

    void Main()
    {
        DerivedClass Instance = new DerivedClass();
    
        Instance.MethodCaller();
    }
    
    
    class InternalBaseClass
    {
        public InternalBaseClass()
        {
    
        }
    
        public virtual void Method()
        {
            Console.WriteLine("BASE METHOD");
        }
    }
    
    class BaseClass : InternalBaseClass
    {
        public BaseClass()
        {
    
        }
    
        public void MethodCaller()
        {
            base.Method();
        }
    }
    
    class DerivedClass : BaseClass
    {
        public DerivedClass()
        {
    
        }
    
        public override void Method()
        {
            Console.WriteLine("DERIVED METHOD");
        }
    }
    
    0 讨论(0)
提交回复
热议问题