我为我的C#项目使用NHibernate,因此我有几个模型类。在C#中调用虚拟方法的替代方法
让我们假设下面的例子:
using System;
namespace TestProject.Model
{
public class Room
{
public virtual int Id { get; set; }
public virtual string UniqueID { get; set; }
public virtual int RoomID { get; set; }
public virtual float Area { get; set; }
}
}
映射这些对象与NHibernate正常工作为止。现在我想要生成一个新的Room对象,并且我想将其存储在数据库中。为避免单独设置每个成员,我在模型类中添加了一个新的构造函数。 下面的虚拟会员我写:
public RoomProperty()
{
}
public RoomProperty(int pRoomId, int pArea)
{
UniqueID = Guid.NewGuid().ToString();
RoomID = pRoomId;
Area = pArea;
}
分析我的代码的FxCop告诉我下面的:
"ConstructorShouldNotCallVirtualMethodsRule"
This rule warns the developer if any virtual methods are called in the constructor of a non-sealed type. The problem is that if a derived class overrides the method then that method will be called before the derived constructor has had a chance to run. This makes the code quite fragile.
This page还介绍了为什么这是错的,我也理解。但我不知道如何解决这个问题。
当我删除所有构造函数,并添加下面的方法...
public void SetRoomPropertyData(int pRoomId, int pArea)
{
UniqueID = Guid.NewGuid().ToString();
RoomID = pRoomId;
Area = pArea;
}
....设置数据后,我打电话的标准构造becaue NHibernate的初始化失败,我不能启动我的aplication。它说:
NHibernate.InvalidProxyTypeException: The following types may not be used as proxies:
VITRIcadHelper.Model.RoomProperty: method SetRoomPropertyData should be 'public/protected virtual' or 'protected internal virtual'
但这种方法设置虚拟将是相同的错误,当我只设置在构造虚拟成员。 如何避免这些错误(侵犯)?
为什么不将值设置为字段而不是属性在构造? – 2013-02-20 14:27:32
@voroninp你无法轻松访问NHibernate的字段 – Andrey 2013-02-20 14:29:39
因为我的模型实际上有大约10个成员,所以我创建了新的房间对象qiet iften。我不想单独设置每个属性。 – Metalhead89 2013-02-20 14:29:43