c# - How to use GetById function in c#
问题描述
I am learning c#. I am trying to create a basic list in a mock repository (Rather than jumping into pulling data from SQL straight away). I have a list that contains cars and has fields such as Id, Model, Make, description etc.
I am then trying to create a method in my Car.CS class, of which gets the car by Id. For example if i pass in the ID of the car, it will return the other details of the car.
Unfortunately when i run the console application, it just returns blank in the console? Could someone let me know where i'm going wrong please?
First of all i have an ICarRepository
namespace GeneralConsoleApp
{
interface ICarRepository
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
and then i have my MockCarRepository of which contains the list
namespace GeneralConsoleApp
{
class MockCarRepository : ICarRepository
{
public IEnumerable<Car> Cars =>
new List<Car>
{
new Car {Id = 1, Name="BMW", Price=23000.00M, Description="BMW car" }
};
public int Id { get; set; }
public string Name {get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
Next is my Car.cs
namespace GeneralConsoleApp
{
class Car
{
private readonly List<Car> CarList = new List<Car>();
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
public Car GetCarById(int Id)
{
return CarList.FirstOrDefault(z => z.Id == Id);
}
}
}
And finally my program.cs main method
namespace GeneralConsoleApp
{
class Program
{
static void Main()
{
Car car = new Car();
Console.WriteLine(car.GetCarById(1));
Console.ReadLine();
}
}
}
解决方案
Your Car
class does not use MockCarRepository
but has it's own empty list instead (CarList
).
You should either populate the list in the Car
or use the mock repository there.
推荐阅读
- java - Apache Poi 无法读取工作表名称
- python - 使用 python 在 macOS 上获取扬声器的内部音频输出
- c# - 如何一次拖放一个文件?
- python - for循环期间的Python标量值错误
- vulkan - 用于间接计算着色器调度的 Vulkan 内存屏障
- eclipse - 严重:Web 应用程序 [/demorest] 中的 Servlet [Jersey Web Application] 引发 load() 异常
- azure - 如何通过powershell触发azure devops管道CI CD
- java - android:allowBackup="true" 不起作用
- firebase - 使用 node.js 的 Firebase Google Analytics
- r - R中的聚类分析:未应用算法时的最佳聚类