我想做一些最通用的事情。 不久,我要打印2份文件:
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>
所以到目前为止我是:
ThirdParty
是否可以简化#region Models
public abstract class ThirdParty
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Student : ThirdParty
{ public DateTime Birthday { get; set; } }
public class Worker : ThirdParty
{ public string Company { get; set; } }
#endregion
#region ViewModels
public abstract class BaseViewModel<T> where T : ThirdParty
{
public T Model { get; set; }
public DateTime SelectedDate { get; set; }
public CultureInfo SelectedCulture { get; set; }
}
public class StudentViewModel : BaseViewModel<Student>
{ public string SchoolInput { get; set; } }
public class WorkerViewModel : BaseViewModel<Worker>
{ public string JobInput { get; set; } }
#endregion
#region Document
public abstract class Document<T>
where T : BaseDocumentViewModel
{
public string Template { get; protected set; }
public string FileName { get; protected set; }
public T DocumentViewModel { get; protected set; }
}
public class StudentDocument : Document<StudentDocumentViewModel>
{
public StudentDocument()
{
Template = "student.docx";
FileName = $"{DocumentViewModel.BaseViewModel.Model.FirstName} {DocumentViewModel.BaseViewModel.Model.LastName}";
}
}
public class WorkerDocument : Document<WorkerDocumentViewModel>
{
public WorkerDocument()
{
Template = "worker.docx";
}
}
#endregion
#region Document ViewModels
public abstract class BaseDocumentViewModel
{
public BaseViewModel<ThirdParty> BaseViewModel { get; set; }
public string PrintingDate { get { return BaseViewModel.SelectedDate.ToString(BaseViewModel.SelectedCulture.DateTimeFormat.ShortDatePattern); } }
}
public class StudentDocumentViewModel : BaseDocumentViewModel
{
public StudentViewModel StudentViewModel { get; set; }
public int Age { get { return DateTime.Now.Year - StudentViewModel.Model.Birthday.Year; } }
}
public class WorkerDocumentViewModel : BaseDocumentViewModel
{
public WorkerViewModel WorkerViewModel { get; set; }
public string Position { get { return $"{WorkerViewModel.Model.Company} - ${WorkerViewModel.JobInput}"; } }
}
#endregion
以使其更通用?需要将BaseDocumentViewModel
描述为一个属性而将另一个属性描述为另一个属性看起来并不那么好。
类似的东西:
BaseViewModel
欢迎任何提示。
答案 0 :(得分:1)
您需要一个具有协变通用参数的接口。
例如IThirdPartyViewModel<out T>
。
这样的事情:
// Entities
public abstract class ThirdParty
{
}
public class Student : ThirdParty
{
}
public class Worker : ThirdParty
{
}
// View models
public interface IThirdPartyViewModel<out T>
{
}
public abstract class ThirdPartyViewModel<T> : IThirdPartyViewModel<T>
{
}
public class StudentVm : ThirdPartyViewModel<Student>
{
}
public class WorkerVm : ThirdPartyViewModel<Worker>
{
}
public abstract class DocumentViewModel<T> where T : IThirdPartyViewModel<ThirdParty>
{
}
public class StudentDocumentVm : DocumentViewModel<StudentVm>
{
}
public class WorkerDocumentVm : DocumentViewModel<WorkerVm>
{
}