C# 为抽象类中的集合设置值时出现问题

C# 为抽象类中的集合设置值时出现问题,c#,generics,reflection,C#,Generics,Reflection,我正在处理一个抽象类上的反射,遇到了一个问题,无法使用PropertyInfo.SetValue方法为现有列表对象赋值 下面是一些(非常)简短的类声明 public abstract class User { } public class Subscriber : User { public string Name { get; set; } public List<string> AttributeList { get; set; } } 公共抽象类用户{} 公共

我正在处理一个抽象类上的反射,遇到了一个问题,无法使用PropertyInfo.SetValue方法为现有列表对象赋值

下面是一些(非常)简短的类声明

public abstract class User { }
public class Subscriber : User
{
    public string Name { get; set; }
    public List<string> AttributeList { get; set; }
}
公共抽象类用户{}
公共类订户:用户
{
公共字符串名称{get;set;}
公共列表属性列表{get;set;}
}
现在在User内部,我有了一个方法,可以从元素数目未知的XML中提取数据。我解析这些元素,如果它们被识别为用户(或其任何子级)的属性,则填充该属性

private void ExtractElement(XElement inner)
{
    // Uses reflection to get the correct Derived class (Initiate, Member, Subscriber)
    Type tUser = this.GetType();

    var prop = tUser.GetProperty("AttributeList"); // hard-coded for brevity
    object value = "Random Value" // same

    var nullableType = Nullable.GetUnderlyingType(prop.PropertyType);
    if (nullableType == null)
        nullableType = prop.PropertyType;


    if (nullableType == typeof(int))
    {
        prop.SetValue(this, int.Parse(value as string), null);
    }
    else if (nullableType == typeof(List<string>))
    {
        var myList = (List<string>)(prop.GetValue(this, null));
        myList.Add(value as string);
        prop.SetValue(this, myList, null); // <- This doesn't save changes.
    }
    else
    {
        prop.SetValue(this, value as string, null);
    }
private void提取器元素(XElement内部)
{
//使用反射获取正确的派生类(Initiate、Member、Subscriber)
Type tUser=this.GetType();
var prop=tUser.GetProperty(“AttributeList”);//为简洁起见,硬编码
对象值=“随机值”//相同
var nullableType=Nullable.getUnderlinegType(prop.PropertyType);
if(nullableType==null)
nullableType=prop.PropertyType;
if(nullableType==typeof(int))
{
prop.SetValue(this,int.Parse(值为字符串),null);
}
else if(nullableType==typeof(List))
{
var myList=(List)(prop.GetValue(this,null));
添加(值为字符串);
prop.SetValue(this,myList,null);//根据请求:

if (nullableType == typeof(List<string>))
{
    ((List<string>)(prop.GetValue(this, null))).Add(value as string);
}
if(nullableType==typeof(List))
{
((列表)(prop.GetValue(this,null))).Add(值作为字符串);
}

你为什么不通过
prop.GetValue(这个,null)
上的反射调用
Add
?我在一个类似的任务中使用了反射,调用
Add
反射效果很好。我只是写了一些代码来测试这个,它似乎工作得很好(继承抽象类的类,抽象类获得其自己的派生属性并执行您在此处执行的任何操作)。我相信你需要在这里提供更多的信息。是的,我的类发生了一些非常奇怪的事情。在第一次传递时,这似乎很好。在其他传递时,列表值不会改变。我将对此进行更深入的研究,并更新我的问题。你实际上是在调用
myList=(作为订阅者).AttributeList;myList.Add(值为字符串);(此为订户)。AttributeList=myList;
最后一条语句没有任何值。AttributeList已设置为myList。没有装箱/取消装箱。装箱和取消装箱发生在值类型上,而不是引用类型上。再次感谢。这一行比我每天的3行冗余代码都要多。