NHibernate异常:方法Add应该是'public / protected virtual'或'protected internal virtual'(NHibernate exception: method Add should be 'public/protected virtual' or 'protected internal virtual')
以此课程为例:
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); } } }当运行没有添加方法的虚拟关键字的应用程序时,出现此错误:
method Add should be 'public/protected virtual' or 'protected internal virtual'
我明白为什么属性需要声明为虚拟的,因为它需要被延迟加载功能覆盖。
但我不明白为什么方法需要被声明为虚拟的...他们需要被推翻为什么?
这很混乱!
Take this class as example:
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); } } }When running the application without the virtual keyword of add method, I getting this error:
method Add should be 'public/protected virtual' or 'protected internal virtual'
I understand why properties need to declare as virtual, because thay need to be overridden by the lazy loading feature.
But I don't understand why Methods need to be declare as virtual... they need to be overridden for what reason?
This very confusing!
最满意答案
方法也需要是虚拟的,因为它们可以访问字段。 考虑这种情况:
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) // ... } }Methods as well need to be virtual because they could access fields. Consider this situation:
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) // ... } }更多推荐
发布评论