C#如何通过存储实例名的字符串变量调用对应类实例的属性
问题原因
你当前写法的错误核心是:secretClass是字符串类型的变量,存储的只是和实例变量名相同的文本内容,本身和你定义的secret1/secret2实例没有任何关联,自然不能直接调用实例的hint1属性。
如果要通过变量名字符串匹配调用对应实例,需要用到反射技术,对初学者来说复杂度高、性能差,当前场景完全没必要使用这种方案。
推荐解决方案(集合存储实例)
直接把你创建的所有SecretWord实例放到数组或者泛型列表中,生成随机索引直接从集合里读取对应实例即可,逻辑简单易懂,代码可维护性更高:
// 将所有谜底实例存入数组 SecretWord[] secrets = new SecretWord[] { new SecretWord("Ape", "It's an animal.", "It climbs trees.", "Planet of the ...", "Looks like human."), new SecretWord("Dog", "It has four legs", "It barks", "Man's best friend", "Woof woof") }; Random rnd = new Random(); // 随机数范围是左闭右开,0到数组长度刚好覆盖所有元素的索引 int randIndex = rnd.Next(0, secrets.Length); // 直接取出随机选中的实例 SecretWord randomSecret = secrets[randIndex]; // 正常读取属性即可 Console.WriteLine(randomSecret.hint1);
反射实现(不推荐初学者使用)
如果你确实需要通过变量名字符串获取实例(当前场景完全没有必要),可以通过反射实现,代码示例如下:
// 假设实例是定义在当前类的字段,获取对应字段信息 var field = this.GetType().GetField(secretClass, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (field != null) { SecretWord target = field.GetValue(this) as SecretWord; Console.WriteLine(target.hint1); }
该方案仅做拓展参考,不建议在当前场景使用:代码复杂度高,容易出现空引用异常,错误只能在运行时发现,性能远低于直接使用集合读取的方案。
内容的提问来源于stack exchange,提问作者Nilsson1188
相关产品推荐
相关产品推荐

