Category.cs
using System.Collections.Generic;
namespace DrinkAndGo1.Data.Models
{
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public List<Drink> Drinks { get; set; }
}
}
ICategoryRepository.cs
using DrinkAndGo1.Data.Models;
using System.Collections.Generic;
namespace DrinkAndGo1.Data.interfaces
{
public interface ICategoryRepository
{
IEnumerable<Category> Categories { get; }
}
}
MockCategoryRepository.cs
using DrinkAndGo1.Data.interfaces;
using DrinkAndGo1.Data.Models;
using System.Collections.Generic;
namespace DrinkAndGo1.Data.mocks
{
public class MockCategoryRepository : ICategoryRepository
{
public IEnumerable<Category> Categories
{
get
{
return new List<Category>
{
new Category(CategoryName = "Alcoholic", Description = "All alcoholic drinks"),
new Category(CategoryName = "None-alcoholic", Description = "All None-alcoholic drinks")
};
}
}
}
}
我的问题是类别和类别名称和描述标记为红色。 MockCategoryRepository.cs不识别类别类中的PROP。 我知道它可以在没有构造函数的情况下识别它
答案 0 :(得分:3)
更改这些行
new Category(CategoryName = "Alcoholic", Description = "All alcoholic drinks"),
new Category(CategoryName = "None-alcoholic", Description = "All None-alcoholic drinks")
以下内容:
new Category{CategoryName = "Alcoholic", Description = "All alcoholic drinks"},
new Category{CategoryName = "None-alcoholic", Description = "All None-alcoholic drinks"}
您正在尝试初始化属性,但是以不正确的方式编写它,如调用构造函数。 MSDN Link
答案 1 :(得分:0)
Samvel使用对象初始化程序展示了一个很好的解决方案,但我想提出另一种选择。如果使用名称和描述初始化Category
是很常见的,为什么不创建一个接受它们的构造函数?
public Category(string name, string description)
{
// TODO: Consider renaming the property to just name, given that the type is Category
CategoryName = name;
Description = description;
}
然后你可以:
return new List<Category>
{
new Category("Alcoholic", "All alcoholic drinks"),
new Category("Non-alcoholic", "All Non-alcoholic drinks")
};
另外,C#6还允许您更简洁地编写属性:
public IEnumerable<Category> Categories => new List<Category>
{
new Category("Alcoholic", "All alcoholic drinks"),
new Category("Non-alcoholic", "All Non-alcoholic drinks")
};