Lam*_*mar 4 c# oop inheritance overriding
这听起来像一个愚蠢的问题,但是我需要编写一个被继承类覆盖的虚拟方法。我不需要虚拟方法具有任何代码,因为该方法完全依赖于继承的类,因此所有代码都将位于重写方法中。
但是,该方法的返回类型不是void。如果我将虚方法保留为空,则会出现错误“没有所有路径都返回值”。
我想到的唯一解决方案是通过返回一个空的空字符串来实现虚拟方法,但是我不认为这是最好的方法。还有其他方法可以用返回类型定义虚拟方法吗?
编辑:
即使大多数答案以他们自己的方式都是正确的,对我的情况也无济于事,因此我添加了代码片段,这些代码片段显示了为什么我需要创建基类的实例,以及为什么我不能使用接口或抽象:
//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();
Run Code Online (Sandbox Code Playgroud)
我知道我将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();
Run Code Online (Sandbox Code Playgroud)
我将CarbineCoder归功于他,因为他是竭尽全力为我提供最接近正确解决方案的人。但是,我感谢大家的贡献。
您可以抛出NotImplementedException而不是返回对象:
public virtual object Method()
{
throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您未在虚拟方法中实现任何东西,则可以创建抽象而不是虚拟方法:
public abstract object Method();
Run Code Online (Sandbox Code Playgroud)
编辑:
另一个选择是为其创建接口。
public interface IMethods
{
object Method();
}
Run Code Online (Sandbox Code Playgroud)
并使您的班级成为该接口的子级。
由于其他答案已经讨论了抽象/虚拟实现,我建议我自己的版本。
你的要求有矛盾。
您可以尝试提取此方法并将其放入接口中吗?
interface NewInterface
{
string NewMethod();
}
public BaseClass
{
...
}
public DerivedClass : BaseClass, NewInterface
{
public string NewMethod
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
如果你能做到这一点,那么你不必担心基类是抽象的/有 NotImplemented 异常,唯一的缺点是每个派生类都应该实现这个接口,但这就是使基类成为非抽象的点。
我没有发现为您的方法实现抽象基类/接口有任何问题。两者都应该可以解决您的问题。
//Parser siteObj = new Parser(); - Dont initialize it here,
//your are initializing it once more below
NewIterface siteObj;
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;
}
Run Code Online (Sandbox Code Playgroud)