【问题标题】:Is there a way to get a property with a variable?有没有办法获得带有变量的属性?
【发布时间】:2019-07-05 17:26:03
【问题描述】:

我有一个 C# 程序,用户可以在配置文件中指定 Windows 声音作为例行程序的一部分播放。我在变量“参数”中有声音,它会像“星号”、“手”、“问题”等。在 Java 中,当我制作 Minecraft 插件时,枚举有一个 .valueOf,我可以传递一个字符串和如果该字符串与枚举名称之一匹配,则返回它。我做了 System.Media.SystemSounds。看看发生了什么。没有类似的功能(我猜这是预期的,因为它不是我假设的枚举)。

有没有一种方法可以轻松地将我的字符串名称转换为匹配的 SystemSound?我的意思是,我可以打开 string.ToLower() 并以这种方式实现,但我希望有一种单线方式。

谢谢!

【问题讨论】:

标签: c#


【解决方案1】:

有没有一种方法可以轻松地将我的字符串名称转换为匹配的 SystemSound

使用Dictionary<string, SystemSounds> 并将所有弦乐和声音插入其中。然后稍后通过字符串键查找声音。

否则,您要查找的术语称为反射-Get property value from string using reflection in C#

【讨论】:

    【解决方案2】:

    如果您以这样的enum 开头:

    public enum Foo
    {
        Bar = 42, Qaz = 99
    }
    

    那么你可以这样做:

    Dictionary<string, Foo> map =
        typeof(Foo)
            .GetEnumValues()
            .Cast<Foo>()
            .Zip(
                typeof(Foo)
                    .GetEnumValues()
                    .Cast<int>(),
                (n, v) => new { n, v })
            .ToDictionary(x => x.n.ToString(), x => (Foo)x.v);
    
    Console.WriteLine((int)map["Bar"]);
    Console.WriteLine((int)map["Qaz"]);
    

    输出:

    42 99

    【讨论】:

      【解决方案3】:

      你可以使用反射。

      enum MyEnum {
        Asterix, Hand, Question
      }
      
      public static void Main(string[] args)
      {
        var field = typeof(MyEnum).GetField("Asterix");
      
        var myEnum = field.GetValue(field);
      
      }
      

      myEnum 变量采用 MyEnum.Asterix 的值,基于提供给 typeof(MyEnum).GetField("Asterix") 方法的字符串变量。

      【讨论】:

        【解决方案4】:

        如果需要按名称访问SystemSounds类的静态属性,可以使用反射,如下:

        var sound = System.Media.SystemSounds.Asterisk;
        Console.WriteLine(sound);
        var name = "Asterisk";
        var soundByName = typeof(System.Media.SystemSounds).GetProperty(name).GetValue(null, null); // null, null because it's a static property
        Console.WriteLine(soundByName);
        Console.WriteLine(sound == soundByName); // Should output 'true'
        

        【讨论】:

          猜你喜欢
          • 2014-04-21
          • 2017-10-22
          • 1970-01-01
          • 2010-11-23
          • 2018-12-05
          • 1970-01-01
          • 1970-01-01
          • 2011-07-25
          • 2019-09-27
          相关资源
          最近更新 更多