我有一个抽象基类,我在扩展程序集中继承它。这是我的代码
region Contract Assembly
public interface IDummy
{
int ForAbstractMethod();
int ForVirtualMethod();
}
public abstract class BaseClass : IDummy
{
public abstract int ForAbstractMethod();
public virtual int ForVirtualMethod()
{
//Some base functionality
return 0;
}
}
#endregion
#region Extension Assembly
public class SomeExtension : BaseClass
{
public override int ForAbstractMethod()
{
//I implement this method here, which is defined abstract in base class and this one works fine.
return 100;
}
public override int ForVirtualMethod()
{
//Even though I override the virtual one here, still the one in the base class executes.
return 1;
}
}
#endregion
#region Main Program Assembly which references Contract Assembly
public class Program
{
void Main()
{
//... compose catalog and other stuff
IDummy dummy = someFactory.GetInstanceFromCatalog<IDummy>();//I get an instance
int a = dummy.ForAbstractMethod();//this works as expected and returns 100
a = dummy.ForVirtualMethod();//here I expect it to return 1 since I overrode it in child class, but it returns still 0.
//...other stuff
}
}
public interface IDummy
{
int ForAbstractMethod();
int ForVirtualMethod();
}
public abstract class BaseClass : IDummy
{
public abstract int ForAbstractMethod();
public virtual int ForVirtualMethod()
{
//Some base functionality
return 0;
}
}
#endregion
#region Extension Assembly
public class SomeExtension : BaseClass
{
public override int ForAbstractMethod()
{
//I implement this method here, which is defined abstract in base class and this one works fine.
return 100;
}
public override int ForVirtualMethod()
{
//Even though I override the virtual one here, still the one in the base class executes.
return 1;
}
}
#endregion
#region Main Program Assembly which references Contract Assembly
public class Program
{
void Main()
{
//... compose catalog and other stuff
IDummy dummy = someFactory.GetInstanceFromCatalog<IDummy>();//I get an instance
int a = dummy.ForAbstractMethod();//this works as expected and returns 100
a = dummy.ForVirtualMethod();//here I expect it to return 1 since I overrode it in child class, but it returns still 0.
//...other stuff
}
}
我不知道覆盖虚拟和抽象方法之间是否存在任何差异,或者这是MEF的特定情况? 谢谢你的帮助...
答案 0 :(得分:3)
您未在ForVirtualMethod
上声明BaseClass
为虚拟广告。将其更改为此
public virtual int ForVirtualMethod()
{
//Some base functionality
return 0;
}
检查MSDN以获取有关虚拟成员声明的更多详细信息
virtual关键字用于修改方法,属性,索引器或事件声明,并允许在派生类中重写它。