public class VMenuInfo : MenuInfo { public MenuInfo _menuInfo { get; set; } public VMenuInfo() { //_menuInfo = this; base.Mkey = _menuInfo.Mkey; base.MUrl = _menuInfo.MUrl; base.Create = _menuInfo.Create; base.MOrder = _menuInfo.MOrder; base.iconUrl = _menuInfo.iconUrl; base.ChangeId = _menuInfo.ChangeId; base.ChangeTime = _menuInfo.ChangeTime; base.IsDeleted = _menuInfo.IsDeleted; base.MId = _menuInfo.MId; base.ParentId = _menuInfo.ParentId; base.MName = _menuInfo.MName; base.ParentName = _menuInfo.ParentName; base.IsTop = _menuInfo.IsTop; base.CreateTime = _menuInfo.CreateTime; } public List<VMenuInfo> children { get; set; } }改进这段代码
时间: 2023-06-13 13:07:22 浏览: 172
首先,无论是继承类还是组合类,都需要在构造函数中对基类或者组合对象进行初始化。但是,在这个代码中,由于没有对_menuInfo进行初始化,所以会导致_nullReferenceException_异常,因此需要在构造函数中给_menuInfo对象赋值:
public class VMenuInfo : MenuInfo
{
public MenuInfo _menuInfo { get; set; }
public VMenuInfo()
{
_menuInfo = new MenuInfo(); //初始化_menuInfo对象
base.Mkey = _menuInfo.Mkey;
base.MUrl = _menuInfo.MUrl;
base.Create = _menuInfo.Create;
base.MOrder = _menuInfo.MOrder;
base.iconUrl = _menuInfo.iconUrl;
base.ChangeId = _menuInfo.ChangeId;
base.ChangeTime = _menuInfo.ChangeTime;
base.IsDeleted = _menuInfo.IsDeleted;
base.MId = _menuInfo.MId;
base.ParentId = _menuInfo.ParentId;
base.MName = _menuInfo.MName;
base.ParentName = _menuInfo.ParentName;
base.IsTop = _menuInfo.IsTop;
base.CreateTime = _menuInfo.CreateTime;
}
public List<VMenuInfo> children { get; set; }
}
另外,由于VMenuInfo及其子类会使用到MenuInfo中的所有属性,因此可以考虑将VMenuInfo中的属性和MenuInfo保持一致,避免不必要的数据冗余和查询更新操作。最终的代码如下:
public class MenuInfo
{
public string Mkey { get; set; }
public string MUrl { get; set; }
public string Create { get; set; }
public int MOrder { get; set; }
public string iconUrl { get; set; }
public long ChangeId { get; set; }
public DateTime ChangeTime { get; set; }
public bool IsDeleted { get; set; }
public int MId { get; set; }
public int ParentId { get; set; }
public string MName { get; set; }
public string ParentName { get; set; }
public bool IsTop { get; set; }
public DateTime CreateTime { get; set; }
}
public class VMenuInfo : MenuInfo
{
public List<VMenuInfo> Children { get; set; }
}
阅读全文