【发布时间】:2016-04-19 10:39:56
【问题描述】:
我是第一次使用 C# 中的重写方法,我认为我对基础知识有很好的掌握。但是我的方法稍微复杂一些,并且在方法中调用了一些方法。
我实际上是想通过找到一种使用基类方法但调用基类方法使用的覆盖方法的方法来节省自己的代码编写。
这是我的问题的一个例子,因为我可能解释得不太好:
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 方法。但是,我希望它使用覆盖的GetName() 方法的结果调用基类GetReference() 方法。
这是正确的路线吗?我一直发现很难在网上找到类似的示例。
任何指针都会很棒!
【问题讨论】:
-
对我来说是正确的,只要您不覆盖
GetReference方法,您将调用基本方法。如果你想覆盖它,你仍然可以使用base.GetReference()。
标签: c# class methods overriding