以这个类为例:
public class Category : PersistentObject<int>
{
public virtual string Title { get; set; }
public virtual string Alias { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ISet<Category> ChildCategories { get; set; }
public /*virtual*/ void Add(Category child)
{
if (child != null)
{
child.ParentCategory = this;
ChildCategories.Add(child);
}
}
}
当运行没有 add 方法的 virtual 关键字的应用程序时,我收到此错误:
method Add should be 'public/protected virtual' or 'protected internal virtual'
我理解为什么属性需要声明为虚拟,因为它们需要被延迟加载功能覆盖。
但我不明白为什么需要将方法声明为虚拟...出于什么原因需要重写它们?
这非常令人困惑!
方法也需要是虚拟的,因为它们可以访问字段。考虑这种情况:
class Entity
{
//...
private int a;
public virtual int A
{
get { return a; }
}
public virtual void Foo()
{
// lazy loading is implemented here by the proxy
// to make the value of a available
if (a > 7)
// ...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)