c# - 通过名称修改类成员值
问题描述
我有这个类项目:
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);
}
}
解决方案
推荐阅读
- python - 我可以在不先绘制直方图的情况下绘制正态概率分布吗?
- spring - 如何配置 Spring MVC 以防止“基于路径的漏洞”
- typescript - 类型上不存在开玩笑的打字稿属性模拟
- google-apps-script - 从 Google 表格创建 Google 日历条目
- ios - 应用程序进入后台时 POST 请求错误
- python - Jupyter Notebook 中的 Flask 应用程序
- c++ - 使用参数化构造函数 C++ 动态分配对象数组
- codeblocks - 使用 sprintf() 时对 __mulhi3 的未定义引用 - Windows 上 Code::Blocks 中的 AVR GCC
- python - 使用 PyGame 中的操纵杆模块
- mysql - SQL Join 2 个表,即使没有匹配的数据