代码之家  ›  专栏  ›  技术社区  ›  Graviton

按属性名称获取静态属性

  •  3
  • Graviton  · 技术社区  · 14 年前

    ImageFormat ,有一些属性,例如 Png , Tiff 等。

    现在,给定一个字符串,是否可以检索相应的静态属性?

    下面是代码

    [Test]
    public void GetPng()
    {
        Assert.AreEqual(ImageFormat.Png, GetImageFormat("Png"));  //how to construct a GetImageFormat function?
    }
    
    3 回复  |  直到 14 年前
        1
  •  2
  •   Julien Roncaglia    14 年前
    static ImageFormat GetImageFormat(string name)
    {
        return (ImageFormat)typeof(ImageFormat)
            .GetProperty(name)
            .GetValue(null, null);
    }
    
        2
  •  4
  •   Leniel Maccaferri    14 年前
    public static void Main()
    {
        typeof(ImageFormat).GetProperty("GetPng", BindingFlags.Public |
                                                  BindingFlags.Static);
    }
    
        3
  •  2
  •   Mark Seemann    14 年前
    PropertyInfo pi =  typeof(ImageFormat)
        .GetProperty("Png", BindingFlags.Static | BindingFlags.Public);