【问题标题】:C# can't reach Enum class variablesC# 无法访问 Enum 类变量
【发布时间】:2017-10-07 00:26:05
【问题描述】:

我创建了以下类:

namespace com.censureret.motions
{
    public class EnumPlayerStances {
        public const int OneHandSword = 50;

        /// <summary>
        /// Friendly name of the type
        /// </summary>
        public static string[] Names = new string[] {
            "One handed Sword"
            };
    }
}

现在我希望在我的以下课程中使用它:

namespace com.censureret.motions{
    public class OneHandSword_Idle : MotionControllerMotion
    {
        public override bool TestActivate()
        {
            if (!mIsStartable) { return false; }
            if (!mMotionController.IsGrounded) { return false; }

            if (mActorController.State.Stance != EnumPlayerStances.OneHandSword)

                return false;
        }

    }
}

但是 Visual Studio 说这是一个错误。

我对 C# 还很陌生。接下来我可以尝试什么?

【问题讨论】:

  • “mActorController.State.Stance”是什么类型?您将它与 EnumPlayerStances 类上的 const int 进行比较。看起来该类可以重构为更加用户友好。值 50 代表什么?您还希望在字符串数组中放入哪些其他内容?

标签: c# namespaces


【解决方案1】:

你打败了枚举的要点。它应该像这样声明和使用:

using System;

namespace StackOverflow_Events
{
    class Program
    {
        static void Main(string[] args)
        {
            string enumName = Enum.GetName(typeof(EnumPlayerStances), EnumPlayerStances.One_Handed_Sword).Replace("_", " ");
            int value = (int)EnumPlayerStances.One_Handed_Sword;
            var example = EnumPlayerStances.One_Handed_Sword;
            switch (example)
            {
                case EnumPlayerStances.One_Handed_Sword:
                    // do stuff
                    break;
            }
            Console.WriteLine($"Name: {enumName}, Value: {value}");
            Console.ReadKey();
        }
    }

    public enum EnumPlayerStances
    {
        One_Handed_Sword = 50
    }
}

请注意,它被声明为“枚举”而不是“类”。

另请注意,如果您声明枚举如下:

public enum EnumPlayerStances
{
    No_Sword, // 0
    One_Handed_Sword, // 1
    Two_Handed_Sword // 2
}

名字的值从 0 开始,后面的每个名字都自动递增 1。

【讨论】:

  • 我认为这不能回答任何问题。它可以被声明为一个枚举,但它不是必须的。以EnumPlayerStances.OneHandSword 访问常量应该可以正常工作。同样GetName 将返回OneHandSword 而不是One handed Sword
  • 如果我提出除此之外的任何其他建议,我会做坏事。当然,您可以使用螺丝刀的枪托来敲钉子。或具有 const 字段作为枚举的类。但是当你向专业人士寻求帮助时,你是在暗示“什么是最好的,或者至少是合理的做法”。然后只有 1 个好的答案可以给出。一锤子钉钉子,一个枚举器枚举。
  • 我看不到枚举的哪些属性可以在无法达到常量时达到它们。当然枚举是组织某些类型常量的更好方法,并且应该给出使用它们的建议,但是当涉及到 OP 显然存在的范围/可访问性问题时,它们并没有更好。他们将声明一个枚举而不是常量,并将他们的问题更改为“C# 无法访问枚举成员”...
  • 谢谢你们的回复。上面的代码是针对 Unity 的。这些有可能以不同的方式工作吗?
  • @MarcRasmussen 为什么不用您收到的错误消息更新问题?因为您的原始代码实际上很好,假设mActorController.State.Stanceint。另外,您可能会稍微澄清一下您的问题,因为您多次提及Enum,但没有使用一次。
猜你喜欢
  • 2018-10-17
  • 2014-06-04
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
  • 2014-08-22
  • 2022-11-18
  • 2015-12-07
  • 1970-01-01
相关资源
最近更新 更多