gpt4 book ai didi

c# - 在数据模型类的属性中包含一些逻辑代码是否可以?

转载 作者:太空狗 更新时间:2023-10-29 21:55:42 24 4
gpt4 key购买 nike

我正在学习 MVC 3,但我没有发现有人在数据模型类的属性中使用某些逻辑代码。

他们做数据模型类如下(举例):

public class Customer
{
public int CustomerId {get;set;}
//other properties without any logic code.
}

是否可以在属性中包含如下逻辑代码?

public class Customer
{
private int customerId;
public int CustomerId {
get{return customerId;}
set
{
customerId=value;
// some logic codes go here.
}
}
//other properties go here.
}

编辑 1:

这是我的真实场景:

子表数据模型:

namespace MvcApplication1.Models
{
public class Choice
{
public int ChoiceId { get; set; }
public string Description { get; set; }
public bool IsCorrect { get; set; }
public QuizItem QuizItem { get; set; }
}
}

父表数据模型:

namespace MvcApplication1.Models
{
public class QuizItem
{
public int QuizItemId { get; set; }
public string Question { get; set; }

private IEnumerable<Choice> choices;
public IEnumerable<Choice> Choices
{
get { return choices; }

set
{
choices = value;
foreach (var x in choices)
x.QuizItem = this;
}
}
}
}

消费者:

namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{


var data = new List<QuizItem>{
new QuizItem
{
QuizItemId = 1,
Question = "What color is your hair?",
Choices = new Choice[]{
new Choice{ ChoiceId=1, Description="Black.", IsCorrect=true},
new Choice{ ChoiceId=2, Description="Red.", IsCorrect=false},
new Choice{ ChoiceId=3, Description="Yellow.", IsCorrect=false}
}
},
new QuizItem
{
QuizItemId = 2,
Question = "What color is your noze?",
Choices = new Choice[]{
new Choice{ChoiceId=1, Description="Pink.", IsCorrect=false},
new Choice{ChoiceId=2, Description="Maroon.", IsCorrect=true},
new Choice{ChoiceId=3, Description="Navy Blue.", IsCorrect=false}
}
}
};


return View(data);
}

}
}

最佳答案

这需要一个方法。两个原因:

  • 我不推荐 Collections 的 setter
    • Property Usage Guidelines - 每次设置属性时都为集合中的每个项目设置属性是昂贵的,不应该在属性中。首选方法。
  • setter 中的代码(在你的情况下)会导致足够的副作用,从而取消使用属性的资格

我建议如下:

public class QuizItem
{
public int QuizItemId { get; set; }
public string Question { get; set; }

private IEnumerable<Choice> choices;
public IEnumerable<Choice> Choices
{
get { return choices; }
}

public void SetChoices(IEnumerable<Choice> choices)
{
foreach (var x in choices)
x.QuizItem = this;

this.choices = choices;
}
}

关于c# - 在数据模型类的属性中包含一些逻辑代码是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4920470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com