覆盖c#中的类并访问使用覆盖方法的虚方法

时间:2016-04-19 10:39:56

标签: c# class methods override

我第一次使用C#中的重写方法,我认为我已经掌握了基础知识。但是我的方法稍微复杂一些,并且方法中有一些调用方法。

我本质上是试图通过查找使用基类方法的方法来保存自己的代码编写,但是调用基类方法使用的overriden方法。

这是我的问题的一个例子,因为我可能不会很好地解释它:

namespace exampleCode
{
    public class BaseClass : AnotherClass
    {
        public static string OrderStorageContainer = "Deliverables";

        public virtual string CustomerStorageContainer = "CustomerDocs";

        public virtual string GetSomething(typeStorage st, string FileName)
        {
            if (String.IsNullOrWhiteSpace(FileName))
            {
                throw new ArgumentNullException("FileName", "The filename of the file should be supplied!");
            }

            var c = GetReference(GetName(st));        
            return c.ToString();
        }
        public virtual string GetName(typeStorage st)
        {
            switch (st)
            {
                case typeStorage.CustomerProvided:
                    return CustomerStorageContainer.ToLower();
                case typeStorage.SystemGenerated:
                    return OrderStorageContainer.ToLower();
            }
            throw new InvalidOperationException("No container defined for storage type: " + st.ToString());
        }

        public virtual string GetReference()
        {
            //does stuff
        }
    }

    public class DervivedClass : BaseClass
    {
        public static string QuoteStorageContainer = "QuoteDeliverables";

        public override string CustomerStorageContainer = "QuoteCustomerDocs";

        public override string GetSomething(typeStorage st, string FileName)
        {
            if (String.IsNullOrWhiteSpace(FileName))
            {
                throw new ArgumentNullException("FileName", "The filename of the file should be supplied!");
            }

            var c = GetReference(GetName(st));        
            return c.ToString();
        }

        public override string GetName(typeStorage st)
        {
            switch (st)
            {
                case typeStorage.CustomerProvided:
                    return CustomerStorageContainer.ToLower();
                case typeStorage.SystemGenerated:
                    return QuoteStorageContainer.ToLower();
            }
            throw new InvalidOperationException("No container defined for storage type: " + st.ToString());
        }

    }
}

基本上,我希望Derived类使用覆盖GetSomething方法。但是,我希望它使用覆盖GetReference()方法的结果调用基类GetName()方法。

这是沿着正确的方向吗?我发现很难在网上找到类似的例子。

任何指针都会很棒!

2 个答案:

答案 0 :(得分:2)

您的实施似乎是正确的。在您不要覆盖DerivedClass中的GetReference()方法之前,这是正确的。

如果您希望var c = GetReference(GetName(st));此行始终调用基类,则应将其写为base.GetReference(GetName(st))

,以采取预防措施

答案 1 :(得分:1)

我认为你走在正确的轨道上。你最好使用base,这样可以避免混淆并强制编译器使用你想要的实现。