【问题标题】:Displaying an object's variable values that are not equal to 0显示不等于 0 的对象的变量值
【发布时间】:2014-01-23 00:34:40
【问题描述】:

我在弄清楚如何显示不等于 0 的对象的统计数据时遇到了问题。基本上我有一个 Item 类,其中包含 50 多个变量,如力量、敏捷、智力等……默认为等于0. 每次单击按钮时,它都会生成一个对象,并为该对象的一些属性赋予非零值(也就是力量现在是 3,敏捷现在是 2,其他一切都保持为 0)。

在我的 GUI 脚本中,单击生成的项目后,我希望它显示项目的详细信息。如果对象的属性不为 0,我只希望它显示对象的属性。这样我就没有 50 多行属性在项目上说它的值只是 0。

该项目的详细信息的 sn-p 如下(注意它编译和运行良好):

public void LootDetailWindow(int id)
{
    GUI.Label(new Rect(10, 15, 150, 80), "<color=white><size=15>" + item.Name + "</size></color>");
    GUI.Label(new Rect (10, 50, 100, 100), item.Icon);
    GUI.Label (new Rect (150, 50, 200, 100), "Level Requirement: " + item.Reqlvl.ToString() + "\nSell Value: " + item.Value);

    //here I want to create a label that for every value that is not 0, to display it.
}

那么我将如何遍历每个属性并检查它是否为 0?提前致谢。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:
    foreach (PropertyInfo prop in obj.GetType().GetProperties(
        BindingFlags.Public | BindingFlags.Instance))
    {
        if (prop.PropertyType != typeof(int)) continue;
    
        int val = (int)prop.GetValue(obj);
        if(val != 0) Console.WriteLine("{0}={1}", prop.Name, val);
    }
    

    【讨论】:

      【解决方案2】:

      我基本同意上述观点,但也考虑.. 你有一个有 50 多个 int 字段的类,大多数是 0 blah blah 至少考虑一下,如果您要倾向于枚举其字段,或者可能会定期添加新属性,那么用字典替换该类可能会更好,即

      enum attributeTypes
      {
          strength,
          agility,
          ...
      }
      

      并将您的硬编码字段替换为

      Dictionary<attributeTypes, int>
      

      因为您希望它们默认为 0,所以这可能会很好地工作

      可能不是当然取决于上下文,但可能......

      【讨论】:

        【解决方案3】:

        你可以make a custom attribute,用那个属性装饰你感兴趣的成员,然后use reflection to iterate over the members that have your custom attribute

        反射比较慢,记得cache the list of conforming members after the first time

        获得成员列表后,您可以获取他们的姓名and actual values for your current object 并执行您的演示逻辑。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多