1

我正在制作一个简单的 Web 表单来收集客户数据并将其输入数据库。我有 5 个子类:CustomerBankEmployeeOwnerTradeReference它们继承自抽象类DataEntry. DataEntry有一个功能public void InsertSelfIntoDataBase(int id);。id 参数是 Customers 表中的主键(Bank、Employee、Owner 和 TradeReference 与 Customer 具有多对一关系),因此Customer不需要插入 id(CustomerID 在数据库中自动递增) )。

目前,我的代码设置为Bank, Employee, Owner, 并在父类中TradeReference实现InsertSelfIntoDataBase函数,同时Customer抛出 NotImplementedException,因此Customer类代码的代码看起来有点像这样:

public int InsertSelfIntoDataBase()
{
    int customerID = InsertCustomerAndReturnScalor();
    return customerID;
}


public override void insertSelfIntoDataBase(int id)
{    throw new NotImplementedException("Customer does not use this function");    }

这个实现是有效的,但它让我觉得我必须使用 NotImplementedException;就像我无法摆脱那种感觉,我的大学教授不知何故知道并在默默地评判我。有没有更好的方法来做到这一点?

4

2 回答 2

5

不管 Robert Columbia 指出的关于类设计的注意事项如何,我想谈谈我对NotImplementedException.

在 .NET Framework 中有另一个众所周知的异常,它更适合此目的 - NotSupportedException. 它表明实现不支持操作 -而是设计而不是缺少实现功能的代码。

NotImplementedException更像是一个指标,表明未来将会而且应该进行实施

于 2016-08-29T15:27:01.397 回答
2

这种情况可能表明抽象类模型不太理想。也许您可以DataEntry在没有该insertSelfIntoDataBase(int)方法的情况下实现抽象类,然后派生第二个抽象类,例如SelfInsertingDataEntry : DataEntry定义抽象方法的抽象类,insertSelfIntoDataBase(int)以便具体类可以根据它们是否实现该方法从任一抽象类继承。

使用这个技巧,与其他方法相关的多态性将被保留,因为任何具体实例(无论它是否实现insertSelfIntoDataBase)都可以转换为 type DataEntry

@Recursive 在评论中也有一个很好的观点,建议将insertSelfIntoDataBase方法移动到接口中。然后,您可以使您的DataEntry类层次结构与条目类型分类严格相关,并允许一些、没有或所有后代实现或不实现接口,而无需他们切换其父级。

于 2016-08-29T15:13:13.927 回答