繁体   English   中英

.NET MVC - 使用类作为模型?

[英].NET MVC — Use a class as the model?

在我的MVC应用程序中,几个视图模型几乎完全相同。 而不是每次复制模型,我想我可以创建一个类而不是。 我不确定的是如何在每个模型中包含该类。

例如,假设我的模型看起来像这样:

public class AccountProfileViewModel
{
    public string FirstName { get; set; }
    public string Lastname { get; set; }
    public AccountProfileViewModel() { }
}

但我知道FirstName和LastName将在许多模型中广泛使用。 所以,我在其中创建了一个带有AccountProfile的类库:

namespace foobar.classes
{
    public class AccountProfile
    {
        public string FirstName { get; set; }
        public string Lastname { get; set; }
    }
}

回到模型中,我将如何包含该类,以便FirstName和LastName在模型中,但不是专门创建的?

创建一个Base类,然后使用继承,您可以访问这些公共属性。

public class AccountProfile
    {
        public string FirstName { get; set; }
        public string Lastname { get; set; }
    }

public class OtherClass : AccountProfile 
    {
        //here you have access to FirstName and Lastname by inheritance
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    }

除了使用继承之外,您还可以使用合成来实现相同的目标。

请参阅优先于继承的组合

它会是这样的:

public class AccountProfile
{
    public string FirstName { get; set; }
    public string Lastname { get; set; }
}

public class AccountProfileViewModel
{
    // Creates a new instance for convenience
    public AnotherViewModel() { Profile = new AccountProfile(); }

    public AccountProfile Profile { get; set; }
}

public class AnotherViewModel
{
    public AccountProfile Profile { get; set; }

    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

您还可以实现类似IProfileInfo的接口,这可能更好,因为类可以实现多个接口但只能从一个类继承。 在将来,您可能希望在需要继承它的代码中添加一些其他统一的方面,但您可能不一定需要从具有Firstname和Lastname属性的基类继承的某些类。 如果您正在使用visual studio,它将自动为您实现接口,因此不会涉及真正的额外工作。

public class AccountProfile : IProfileInfo
{
    public string FirstName { get; set; }
    public string Lastname { get; set; }
}

public interface IProfileInfo 
{
    string Firstname {get;set;}
    string Lastname {get;set;}
}

这太长了,不能留在评论中,所以这只是基于你已经收到的答案的评论。

如果您创建的新类基本上只是略有不同的对象类型,则应该只使用继承。 如果您尝试将2个单独的类关联在一起,则应使用属性方法。 继承就像是

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DOB { get; set; }
}

public class Teacher : Person 
{
    public string RoomNumber { get; set; }
    public DateTime HireDate { get; set; }
}

public class Student : Person
{
    public string HomeRoomNumber { get; set; }
    public string LockerNumber { get; set; }
}

组合应该像这样使用。

public class Address 
{
    public string Address1 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

public class StudentViewModel
{
    public StudentViewModel ()
    {
        Student = new Student();
        Address = new Address();
    }
    public Student Student { get; set; }
    public Address Address { get; set; }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM