相关疑难解决方法(0)

初始化没有"新列表"的列表属性会导致NullReferenceException

using System;
using System.Collections.Generic;

class Parent
{
   public Child Child { get; set; }
}

class Child
{
   public List<string> Strings { get; set; }
}

static class Program
{
   static void Main() {
      // bad object initialization
      var parent = new Parent() {
         Child = {
            Strings = { "hello", "world" }
         }
      };
   }
}
Run Code Online (Sandbox Code Playgroud)

上面的程序编译很好,但在运行时崩溃,而Object引用没有设置为对象的实例.

如果您在上面的代码段中注意到,我在初始化子属性时省略了new.

显然,正确的初始化方法是:

      var parent = new Parent() {
         Child = new Child() {
            Strings = new List<string> { …
Run Code Online (Sandbox Code Playgroud)

c# nullreferenceexception

22
推荐指数
4
解决办法
2078
查看次数

继承List <T>来实现集合是个坏主意吗?

我曾经读过Imaar Spaanjars关于如何构建3层应用程序的文章.(http://imar.spaanjaars.com/416/building-layered-web-applications-with-microsoft-aspnet-20-part-1)这已成为我编码的基础.

因此,我通过继承a来实现集合List<T>.因此,如果我有一个名为Employee的类,要实现一个集合,我还将有一个Employees类,如下所示.

class Employee
{
   int EmpID {get;set;}
   string EmpName {get;set;}  

}

class Employees : List<Employee>
{
   public Employees(){}
}
Run Code Online (Sandbox Code Playgroud)

我从来没有真正质疑这一点,因为它为我做了工作.但是现在我开始尝试一些事情,我不确定这是否是正确的方法.

例如,如果我想从Employees获得一个子集,例如

 Employees newEmployees = (Employees) AllEmployees.FindAll(emp => emp.JoiningDate > DateTime.Now);
Run Code Online (Sandbox Code Playgroud)

这会抛出System.InvalidCastException.但是,如果我使用以下内容则没有问题.

List<Employee> newEmployees = AllEmployees.FindAll(emp => emp.JoiningDate > DateTime.Now);
Run Code Online (Sandbox Code Playgroud)

那么我该如何实现Employees以便我不必List<Employee>在DAL或BLL中明确使用?或者我怎么摆脱InvalidCastexception?

c# collections list

12
推荐指数
2
解决办法
9357
查看次数

标签 统计

c# ×2

collections ×1

list ×1

nullreferenceexception ×1