所以我有一个名为“Account”的抽象类:
public abstract class Account
{
private string _FinancialInstitution;
public string FinancialInstitution
{
get { return _FinancialInstitution; }
...
}
}
我还有另外两个类,它们来自这两个:
public class CreditCard : Account
{
private DateTime _ExpirationDate;
...
}
和这一个:
public class CheckingSavingsAccount : Account
{
private string _PrimaryAccountHolder;
...
}
现在,重点是能够在泛型集合列表中存储任何类型的帐户,但如果我尝试这样做:
List<Account> lstTemp = new List<Account>();
CreditCard newCC1 = new CreditCard();
lstTemp.Add(new CreditCard());
我得到了一个“对象引用未设置为对象的实例”。尝试添加新创建的信用卡对象(lstTemp.Add)的行上的错误。我做错了什么?
这是一个例外细节:
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."
Source="mscorlib"
StackTrace:
at System.Collections.Generic.List`1.Add(T item)
at RunAsConsole.Program.Main(String[] args) in C:\Users\ortegae\Documents\Visual Studio 2008\Projects\eStocks50600\RunAsConsole\Program.cs:line 52
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
答案 0 :(得分:1)
public abstract class Base {}
public class D1 : Base {}
public class D2 : Base {}
[Test]
public void Test_Generic_Lists_With_Abstract_Base()
{
var list = new List<Base>();
list.Add(new D1());
list.Add(new D2());
Assert.That(list[0] is D1);
Assert.That(list[1] is D2);
}
编辑您的堆栈跟踪与您显示的代码不对齐。 new的返回永远不会为null,并且您的堆栈跟踪显示传入了null。我们还缺少什么?
答案 1 :(得分:0)
如果您有Account()或CreditCard()
的构造函数public Account()
{
...
}
public CreditCard()
{
...
}
然后可能是异常被抛出。您可能希望使用Visual Studio调试器进行检查,看看发生了什么。
一个有用的提示,BTW,是将Visual Studio设置为中断所有异常,无论是处理还是未处理。在Debug下,选择Exceptions ...,然后在Common Language Runtime Exceptions旁边,确保设置了Thrown下的复选框。