使用属性列表

时间:2011-04-06 10:01:22

标签: c#

我想填写一些属性。我从XML文件中获取数据,我使用LINQ to XML读取。

看起来像那样:

var CharNames = from CharName in doc.Descendants("character").Attributes("name")
                select CharName;

我的属性看起来像这样:

public List<int> CharClassId { get; set; }
public List<String> CharRace { get; set; }
public List<int> CharRaceId { get; set; }
public List<int> CharGenderId { get; set; }

然后我想填写这个属性..实际上我使用一个简单的foreach

foreach (String s in CharNames)
{
    CharName.Add(s);
}

当然我得到NullReferenceException,因为List没有初始化。

但我无法使用

初始化它
CharName = new List<String>();

什么是好的解决方案?

也许我的工作方式绝对错误......如果是这样,请告诉我

THX

修改

好的,我得到了解决方案。 我只是使用.NET 2.0属性样式,并使其像:

    private List<String> _CharName;
    public List<string> CharName 
    {
        get
        {
            if (_CharName == null)
                _CharName = new List<string>();
            return _CharName;
        }
        set
        {
            _CharName = value;
        }
    }

现在我的列表已被xml中的所有名称填充。

非常感谢=)

2 个答案:

答案 0 :(得分:1)

只需在构造函数中初始化它。

答案 1 :(得分:0)

List<String> CharNames = new List<String>();

CharNames = (from CharName in doc.Descendants("character").Attributes("name")
             select CharName).ToList();