有没有一种方法可以访问类的成员,在访问时使用字符串而不是类名

我希望使用一些反射来访问类中的所有成员并获取它们的值。这是班级的。我总是初始化“Championsids”类。(我知道有很多代码,但它非常简单)。

当我初始化它时,值会自动分配给所有成员。一切正常


ChampionIds championIds = JsonConvert.DeserializeObject<ChampionIds>(json2); //Assignment works perfect!

现在我可以这样访问所有值。仅作为使用示例


Console.WriteLine(championIds.data.Aatrox.id);

Console.WriteLine(championIds.data.Aatrox.key);


Console.WriteLine(championIds.data.AurelionSol.version);

Console.WriteLine(championIds.data.AurelionSol.title);

但问题是我想将所有不同的冠军键和名称放入字典中。所以像这样的事情。


Dictionary<string, string> ChampIdDict = new Dictionary<string, string>();

ChampIdDict.Add(championIds.data.Aatrox.key, championIds.data.Aatrox.name);

我想为每个冠军做到这一点。对于这样的例子


Dictionary<string, string> ChampIdDict = new Dictionary<string, string>();

ChampIdDict.Add(championIds.data.Aatrox.key, championIds.data.Aatrox.name);

ChampIdDict.Add(championIds.data.Ahri.key, championIds.data.Ahri.name);

ChampIdDict.Add(championIds.data.Akali.key, championIds.data.Akali.name);

//and so on

但我不想以这种方式在我的代码中编写 100 行。所以我遍历所有成员并使用此代码轻松获取他们的名字


FieldInfo[] fields = typeof(Data).GetFields();

foreach (var field in fields)

{

     Console.WriteLine(field.Name);

}

结果是这样的


Aatrox

Ahri

Akali

Alistar

Amumu

Anivia

//and so on

我该怎么做才能做到这一点


FieldInfo[] fields = typeof(Data).GetFields();

foreach (var field in fields)

{

    Console.WriteLine("Inserting champion = " + field.Name + " into the dictionary");

    string key = championIds.data.(field.Name).key;

    string name = championIds.data.(field.Name).name;

    ChampIdDict.Add(key, name)

}

结果是我简单地从网站获取冠军 id,然后我说 string returnedChampionId = //from website ex. 第266章 266


谢谢阅读。希望你能推荐一些东西


繁花不似锦
浏览 77回答 1
1回答

子衿沉夜

您需要从每个字段获取值并将其转换为适当的类型。然后就可以访问内部属性了Data actualDataObject = // whereever you get it fromDictionary<string, string> ChampIdDict = new Dictionary<string, string>();FieldInfo[] fields = typeof(Data).GetFields();foreach (var field in fields){&nbsp; &nbsp; Champions temp = (Champions)field.GetValue(actualDataObject);&nbsp; &nbsp; string key = temp.key;&nbsp; &nbsp; string name = temp.name;&nbsp; &nbsp; ChampIdDict.Add(key, name)}在 linq 中,这可能看起来像这样:Dictionary<string, string> ChampIdDict = (from field in fields&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let temp = (Champions)field.GetValue(actualDataObject)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select new {key = temp.key, name = temp.name})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.ToDictionary(x => x.key, x => x.name);
打开App,查看更多内容
随时随地看视频慕课网APP