我有以下代码:
List<MultiServiceRequestMember> _memberList = new List<MultiServiceRequestMember>();
var type = Type.GetType(svc.NotificationClassName); <- this is a string of the class name.
MultiServiceRequestMember newMember = (MultiServiceRequestMember)Activator.CreateInstance(type);
_memberList.add(newMember);
MultServiceRequestMember是基本类型,我想为特定于type
的属性赋值。我的问题是:如何转换newMember以输入和访问其属性?
答案 0 :(得分:3)
如何投射newMember以输入并访问它的属性?
你不能强制它,因为你在编译时不知道具体的类型。如果你这样做,你首先不需要反思!
您还必须通过反射设置属性:
// TODO: Checking that you managed to get the property, that's it's writable etc.
var property = type.GetProperty("PropertyName");
property.SetValue(newMember, "new value", null);
答案 1 :(得分:0)
您必须将代码更改为如下所示:
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。