创建通用类以更新几个类的属性

时间:2018-10-22 13:06:58

标签: c# generics

我有一个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;
   }
}

(最终,那些用于名称和电子邮件的硬编码值将被已认证的用户信息取代,因此我将不得不将它们作为一个单独的问题引入服务中)

谢谢!

2 个答案:

答案 0 :(得分:0)

为什么不在构造函数中传递值

# Error pages
error_page 500 502 503 504 /500.html;
location = /500.html {
    root /home/ubuntu/this_proj/project_dir/templates/;
}

location = /too_bad.svg {
    root /home/ubuntu/this_proj/project_dir/static/img/;
}

然后

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; }
}

答案 1 :(得分:0)

在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;
}