您必须将代码更改为如下所示:
List<MultiServiceRequestMember> _memberList = new List<MultiServiceRequestMember>();
var type = Type.GetType(svc.NotificationClassName);
MultiServiceRequestMember newMember = null;
if (type == typeof(MultiServiceRequestMemberA))
{
newMember = new MultiServiceRequestMemberA();
//set specific properties
}
else if (type == typeof(MultiServiceRequestMemberB)) //etc.
{
//...
}
else
{
//throw or some default
}
_memberList.add(newMember);
但是,它看起来像代码异味。我猜你正在尝试基于其他对象初始化一个对象(我们称之为 NotificationInfo)。然后代替看起来像这样的代码:
if (type == typeof(MultiServiceRequestMemberA))
{
newMember = new MultiServiceRequestMemberA();
newMember.A = notificationInfo.A;
}
也许应该考虑以下设计:
class MultiServiceRequestMember
{
public virtual void Initialize(NotificationInfo notificationInfo) //or abstract if you wish
{
}
}
class MultiServiceRequestMemberA : MultiServiceRequestMember
{
public override void Initialize(NotificationInfo notificationInfo)
{
base.Initialize(notificationInfo);
this.A = notificationInfo.A;
}
}
然后您就可以保留之前的代码,只需调用 Initialize。