【发布时间】:2014-10-23 08:08:40
【问题描述】:
这听起来像是一个愚蠢的问题,但我需要编写一个被继承类覆盖的虚拟方法。我不需要虚拟方法有任何代码,因为这个方法完全依赖于继承的类,因此所有代码都将在覆盖方法中。
但是,该方法的返回类型不是 void。如果我将虚拟方法保持为空,它会给我一个错误“没有所有路径都返回值”。
我想出的唯一解决方案是通过返回一个虚拟的空字符串来实现虚拟方法,但我觉得这不是最好的方法。有没有其他方法可以定义返回类型的虚方法?
编辑:
即使大多数答案在他们自己的方式上都是正确的,但它们对我的情况没有帮助,因此我添加了代码的 sn-ps 来说明为什么我需要创建基类的实例,以及为什么我不能使用接口或抽象:
//base class
public class Parser
{
public virtual string GetTitle()
{
return "";
}
}
//sub class
public class XYZSite : Parser
{
public override string GetTitle()
{
//do something
return title;
}
}
// in my code I am trying to create a dynamic object
Parser siteObj = new Parser();
string site = "xyz";
switch (site)
{
case "abc":
feedUrl = "www.abc.com/rss";
siteObj = new ABCSite();
break;
case "xyz":
feedUrl = "www.xzy.com/rss";
siteObj = new XYZSite();
break;
}
//further work with siteObj, this is why I wanted to initialize it with base class,
//therefore it won't break no matter what inherited class it was
siteObj.GetTitle();
我知道我将 Parser 对象转换为 Site 对象的方式似乎不是很理想,但这是它对我有用的唯一方式,所以请随时纠正您在我的代码中发现的任何错误。
编辑(解决方案)
我通过使用接口和抽象遵循了许多回复的建议。但是,只有当我将基类及其所有方法更改为抽象,并从接口继承基类,然后从基类继承子类时,它才对我有用。只有这样我才能确保所有类都有相同的方法,这可以帮助我在运行时生成变体对象。
Public interface IParser
{
string GetTitle();
}
Public abstract class Parser : IParser
{
public abstract string GetTitle();
}
Public class XYZ : Parser
{
public string GetTitle();
{
//actual get title code goes here
}
}
//in my web form I declare the object as follows
IParser siteObj = null;
...
//depending on a certain condition I cast the object to specific sub class
siteObj = new XYZ();
...
//only now I can use GetTitle method regardless of type of object
siteObj.GetTitle();
我将功劳归功于 CarbineCoder,因为他付出了足够的努力让我最接近正确的解决方案。不过我感谢大家的贡献。
【问题讨论】:
-
超类本身不是抽象的。
-
然而它有一个方法,它本身并没有做任何有用的事情,并且每个重写类都应该重写?听起来是不是应该是抽象的?
-
我非常感谢它修复了我的代码逻辑,我想问题的根源在于我首先使用继承的方式。请检查上面的代码。
-
如果
"abc"和"xyz"详尽(即没有使用其他site值),那么只需删除变量声明的= new Parser()部分并将default添加到您的switch中,它会抛出NotSupportedException(以使明确的分配分析变得愉快)。现在可以将基类声明为abstract。
标签: c# oop inheritance overriding