C# 动态创建具有公共属性的对象

C# 动态创建具有公共属性的对象,c#,C#,我想在运行时实例化从同一父类继承的两个类中的一个 这是父类。它具有两个孩子共有的所有属性 public class Applicant { public int ApplicantID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } //etc }

我想在运行时实例化从同一父类继承的两个类中的一个

这是父类。它具有两个孩子共有的所有属性

public class Applicant
{
    public int ApplicantID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    //etc
}
从中继承的两个类具有使它们不同的属性

public class PilotApplicant : Applicant
{
    public byte[] SSN { get; set; }
    public string EthnicExplain { get; set; }
    public byte[] CryptoKey { get; set; }
    public byte[] CryptoIV { get; set; }
}

public class CMSApplicant : Applicant
{
    public string LocationName { get; set; }

}
下面是我想做的,或者类似的事情:

switch (Host)
{
    case "pilot":
        currentApplicant = new PilotApplicant();
        break;

    case "cms":
        currentApplicant = new CMSApplicant();
        break;
}

currentApplicant.ApplicantID = Convert.ToInt32(oReader["ApplicantID"]);
currentApplicant.FirstName = oReader["FirstName"].ToString();
currentApplicant.LastName = oReader["LastName"].ToString();
currentApplicant.MiddleName = oReader["MiddleName"].ToString();

基本上,我试图避免为类单独设置所有属性,因为这两个类的99%属性是相同的。有什么办法可以让我这么做吗?

你现在做的没问题。Juse使用基类并稍微调整它:

//
// Use base class here
//
Applicant currentApplicant;

switch (Host)
{
    case "pilot":
        currentApplicant = new PilotApplicant();
        // set values for pilot
        break;

    case "cms":
        CMSApplicant cmsApplicant = new CMSApplicant();
        currentApplicant = cmsApplicant;
        cmsApplicant.LocationName = (string)oReader["LocationName"];
        break;

    default:
       currentApplicant  = null;
       break;
}

我不理解您的问题,除非您的
currentAppender
变量不是
appender
类型。为什么要将其设置为null。它已经是空的beginning@TGH:否,它未定义。没有它,它甚至无法编译。在正常情况下,会出现一些异常处理。@Patrickhoffman出于某种原因试图在基类中设置LocationName,但给出了一个错误。我将其更改为
currentApplicator=newcmsapplicant{LocationName=oReader[“LocationName”].ToString()成功了。谢谢