无法在ASP.NET中实例化对象

本文关键字:实例化 对象 NET ASP | 更新日期: 2023-09-27 18:24:54

我有一个名为"Repository"的类,它用数据实例化了一些示例类:

public class Repository
{
    // create dictionary collection for prices, and define property to get the collection
    Dictionary<string, int> prices = new Dictionary<string, int>();
    public Dictionary<string, int> Prices { get { return prices; } }
    // create List with Reservations, and define property to get the List 
    List<Reservation> reservations = new List<Reservation>();
    public List<Reservation> Reservations { get { return reservations; } }
    public Repository()
    {
        // add prices to the dictionary, prices
        prices.Add("Dog", 180);
        prices.Add("Cat", 140);
        prices.Add("Snake", 120);
        prices.Add("Guinea pig", 75);
        prices.Add("Canary", 60);
        // create customers
        Customer c1 = new Customer(1, "Susan", "Peterson", "Borgergade 45", "8000", "Aarhus", "supe@xmail.dk", "21212121");
        Customer c2 = new Customer(2, "Brian", "Smith", "Algade 108", "8000", "Aarhus", "brsm@xmail.dk", "45454545");
        Reservation r1 = new Reservation(1, "Hamlet", new DateTime(2014, 9, 2), "Dog", new DateTime(2014, 9, 20), new DateTime(2014, 9, 20), c1);
        Reservation r2 = new Reservation(2, "Dog", new DateTime(2014, 9, 14), "Samson", new DateTime(2014, 9, 21), new DateTime(2014, 9, 21), c1);
        Reservation r3 = new Reservation(3, "Cat", new DateTime(2014, 9, 7), "Darla", new DateTime(2014, 9, 10), new DateTime(2014, 9, 10), c2);
        // add Reservations to list of Reservations with instance name reservations
        reservations.Add(r1);
        reservations.Add(r2);
        reservations.Add(r3);
    }
}

现在我想在视图中显示该数据,所以我尝试在ReservationController中实例化它,并使其可用于视图:

public ActionResult Index()
{
    private Repository repository = new Repository();
    return View(repository.Reservations);
}

这在我尝试实例化Repository:的行上产生了几个错误

找不到类型或命名空间名称"Repository"(您是缺少using指令或程序集引用?)

预期

表达式术语"private"无效

无法在ASP.NET中实例化对象

访问修饰符分配给局部变量是无效的,因此会出现错误。

您需要从局部变量中删除private访问修饰符。

public ActionResult Index()
{
  Repository repository = new Repository();
  return View(repository.Reservations);
}