首页 > 解决方案 > 通过名称修改类成员值

问题描述

我有这个类项目:

public class Item
{
    int TypeID;
    string Name;
    List<string> Flags;
    List<Attribute> Attributes;
}

我正在尝试读取文件并将其解析到该类中。文件如下所示:

TypeID      = 2425
Name        = "an ivory chair"
Flags       = {Avoid,Rotate,Destroy,Height}
Attributes  = {RotateTarget=2423,DestroyTarget=3136}

TypeID      = 2426
Name        = "a small trunk"
Flags       = {Avoid,Destroy,Height}
Attributes  = {DestroyTarget=3136}

TypeID      = 2427
Name        = "a wardrobe"
Flags       = {Container,Unpass,Unmove,Unlay}
Attributes  = {Capacity=6}

所以我的想法是或多或少地像json序列化器那样解析它(我想在之后将它提取为json)。

当我尝试访问一个成员(例如 TypeID 并分配一个值)时,我总是得到 null,我无法获得该成员的句柄,因此我可以访问/修改它:

截屏

这是我的代码尝试:

var path = "items.srv";

// Read file
var lines = File.ReadAllLines(path);

// Make list of attributes
foreach (var line in lines)
{
    Item item = new Item();

    // Parse
    if (line.Contains("TypeID") | line.Contains("Name"))
    {
        string cleaned = line.Replace(" ", "").Replace("\t", "");
        var slices = cleaned.Split('=');
        var property = item.GetType().GetProperty(slices[0]);
        property.SetValue(item, slices[1], null);
    }
}

标签: c#

解决方案


推荐阅读