这可能听起来像一个愚蠢的问题,但我需要编写一个被继承类覆盖的虚方法.我不需要虚方法来获得任何代码,因为这个方法完全依赖于继承的类,因此所有代码都将在override方法中.
但是,该方法的返回类型不是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();
我知道我将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致敬,因为他是那个付出足够努力让我最接近正确解决方案的人.但我感谢大家的贡献.
解决方法
由于其他答案已经讨论过抽象/虚拟实现,我建议我自己的版本.
您的要求存在矛盾.
>您想要一个不是抽象的基类,但它有一个未实现的方法.难道你不认为这个未实现的方法会使类不完整并最终使它成为一个抽象的方法,即使你没有明确说过吗?
>因此,假设您的类永远不会是一个抽象类,将它作为普通类完全合理.从类中完全删除此方法并将其移动到接口是否有意义?
interface NewInterface { string NewMethod(); } public BaseClass { ... } public DerivedClass : BaseClass,NewInterface { public string NewMethod { ... } }
如果你可以这样做,那么你不必担心基类是抽象的/具有NotImplemented异常,只有缺点是每个派生类都应该实现这个接口,但这就是使基类非抽象的观点.
我没有看到为您的方法实现Abstract BaseClass / Interface有任何问题.两者都应该是您问题的解决方案.
//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; }