我爲我的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