单独的视图模型类与具有函数的属性

本文关键字:函数 属性 视图 模型 单独 | 更新日期: 2023-09-27 18:21:35

我想知道是应该只为视图模型创建一个类,还是应该将属性和方法保留在一个类中。对此有最佳实践吗?

下面的示例显示了具有一个单独的视图模型类:

public class vmCustomer
{
    public string FullName { get; set; }
    public string Address { get; set; }
    ...
}
public class Customer
{
     public vmCustomer GetCustomer(decimal id)
     {
           ...
           return customer;
     }
}

下面的例子显示了在一个类中拥有我的属性和方法:

public class Customer
{
     public string FullName { get; set; }
     public string Address { get; set; }
     public Customer GetCustomer(decimal id)
     {
           ...
           return customer;
     }
}

在OOP开发中,有更好的首选吗?SOLID原则会因为单一责任规则而说是一个单独的视图模型吗?

单独的视图模型类与具有函数的属性

ViewModel是视图和模型之间的"桥梁"。真实数据应该在模型中,在视图中,模型数据应该在格式中,这样可以绑定到视图。

另外,根据id选择客户应该在服务类中,由viewmodel调用。

public class VmCustomerDetail
{
    private ICustomerService customerService;
    public Customer CustomerDetail {get; set;}
    public async void Refresh(int id){
        CustomerDetail = customerService.GetById(id);
    }
}
public class Customer
{
     public string FullName { get; set; }
     public string Address { get; set; }    
}
public interface ICustomerService{
    Customer GetById(int id);
}
public class CustomerService : ICustomerService{
    Customer GetById(int id){
       //...
    }
}