[英]create generic class to update properties of several classes
我有一个asp.net核心应用程序,它使用带有以下属性的此类“ Form”:
public abstract class Form
{
public string SentByName { get; set; }
public string SentByEmail { get; set; }
public DateTime ReceivedByDateTime { get; set; }
}
我有几个从该类继承的类(例如):
public class Customer: Form
{
public int Id { get; set; }
public string FirstName{ get; set; }
public string Surname { get; set; }
}
public class Account: Form
{
public int Id { get; set; }
public string AccountIdentifier { get; set; }
public string AccountType { get; set; }
}
想法是将来自视图模型的数据传递到控制器上的create动作,并从视图模型属性中创建一个Customer实例,并在控制器中的某些逻辑旁边将值应用于从Form类继承的属性。
例如。
Customer thisForm = new Customer();
thisForm.FirstName = vm.FirstName;
thisForm.Surname= vm.Surname;
thisForm.SentByEmail = "ds@ds.com";
thisForm.SentByName = "DS";
thisForm.ReceivedByDateTime = DateTime.Now
_IMGP1DFC.Add(thisForm);
因此,您可以想象,对于给定模型进行创建的每个控制器操作,我将一遍又一遍地复制最后三行。
我想做的是创建某种通用服务,任何从Form继承的对象都可以传入,并用特定值更新这三个属性。
谁能告诉我如何创建一个可以接受客户或帐户的类,以便我可以用一个类更新这些相似的属性...例如
public class AttributeMapper {
private SomeKindOfFormObject _aForm;
public AttributeMapper(SomeKindOfFormObject aForm) {
_aForm = aForm;
}
public SomeKindOfFormObject mapIt () {
_aForm.SentByEmail = ....
.....
return aForm;
}
}
(最终,那些名称和电子邮件的硬编码值将被已认证的用户信息代替,因此我将不得不将其作为单独的问题带入服务中)
谢谢!
为什么不在构造函数中传递值
public abstract class Form
{
public Form(string xx, string yy)
{
SentByName = xx;
SentByEmail = yy;
ReceivedByDateTime = Date.Now;
}
}
public class Customer: Form
{
public Customer(string xx, string yy) : base(xx,yy)
{
}
public int Id { get; set; }
public string FirstName{ get; set; }
public string Surname { get; set; }
}
然后
Customer thisForm = new Customer("DS","ds@ds.com" );
//if these values is special for Customer, setting them in constructor
thisForm.FirstName = vm.FirstName;
thisForm.Surname= vm.Surname;
_IMGP1DFC.Add(thisForm);
在Form中创建一个可填充属性的构造函数
public abstract class Form
{
public string SentByName { get; set; }
public string SentByEmail { get; set; }
public DateTime ReceivedByDateTime { get; set; }
public Form()
{
this.SentByEmail = "ds@ds.com";
this.SentByName = "DS";
this.ReceivedByDateTime = DateTime.Now
}
}
然后使继承的构造函数像这样:
public class Customer: Form
{
public int Id { get; set; }
public string FirstName{ get; set; }
public string Surname { get; set; }
public Customer() : base()
{
}
}
或者,如果您使用的是最新版本的C#,请尝试以下操作:
public abstract class Form
{
public string SentByName { get; set; } = "ds@ds.com";
public string SentByEmail { get; set; } = "DS";
public DateTime ReceivedByDateTime { get; set; } = DateTime.Now;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.