0

我有以下代码:

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 来输入和访问它的属性?

4

2 回答 2

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);
于 2012-05-06T08:56:53.153 回答
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。

于 2012-05-06T08:59:02.113 回答