【问题标题】:Want to use a string to name a new instance of a class dynamically想要使用字符串动态命名类的新实例
【发布时间】:2013-06-13 03:20:21
【问题描述】:

好的,这可能是不可能的,但我想使用一个字符串作为函数的参数,并使用该字符串来命名一个类的新实例。使用带有 C# XNA 的 Visual Studios 2010,我尝试使用 google 和 here 搜索解决方案,但也许我没有使用正确的关键字或其他东西。

     public void createRace(string raceName, Element element1, Element element2, AbilityScore stat1, AbilityScore stat2, AbilityScore stat3, AbilityScore stat4)
    {
        Race temp = new Race();
        temp.raceName = raceName;
        temp.primaryElement = element1;
        temp.secondaryElement = element2;
        temp.primaryAbility = stat1;
        temp.secondaryAbility1 = stat2;
        temp.secondaryAbility2 = stat3;
        temp.weakAbility = stat4;
    }

我希望 Race temp 在命名 Race 的新实例时使用 raceName 而不是 temp,如果不可能,请告诉我,我会找到解决方法。

【问题讨论】:

  • 你为什么需要这个要求,编译器不会真正关心你命名变量的原因
  • 这是不可能的(因为变量名是编译时,但变量的值是运行时),但是由于您没有解释为什么您希望该名称不同,因此不清楚是什么是适当的解决方法。 TGH 建议的Dictionary 可能是您想要的...
  • 有人可能会争辩说,您可以使用构造函数(或对象初始化器)来创建 Race 的实例 - 而且您根本不需要 createRace 方法。

标签: c# string function xna naming


【解决方案1】:

我会使用字典来解决这个问题。以下代码将允许您基于“raceName”访问您的实例

Dictionary<string,Race> races = new Dictionary<string,Race>();

  public void createRace(string raceName, Element element1, Element element2, AbilityScore stat1, AbilityScore stat2, AbilityScore stat3, AbilityScore stat4)
    {
        Race temp = new Race();
        temp.raceName = raceName;
        temp.primaryElement = element1;
        temp.secondaryElement = element2;
        temp.primaryAbility = stat1;
        temp.secondaryAbility1 = stat2;
        temp.secondaryAbility2 = stat3;
        temp.weakAbility = stat4;

        races.Add(raceName,temp);
    }

【讨论】:

  • 谢谢,这似乎有效,老实说,没想到会有这么快的反应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
  • 1970-01-01
  • 2016-07-25
  • 2021-06-25
相关资源
最近更新 更多