简体   繁体   English

如何使用反射从静态类获取静态属性

[英]How to get static properties from static class using reflection

I've got a static class with static getters. 我有一个带有静态吸气剂的静态类。

public static class Cars
{
   public static KeyValuePair<Guid, string> Acura
   {
       get { return new KeyValuePair<Guid, string>(new Guid("MMMMMMMM-509B-477A-ADB1-5CD014B41001"), "Acura"); }
   }
   public static KeyValuePair<Guid, string> AlfaRomeo
   {
      get { return new KeyValuePair<Guid, string>(new Guid("MMMMMMMM-509B-477A-ADB1-5CD014B41002"), "Alfa Romeo"); }
   }
   // etc.
}

I need to retrieve all the static properties from this static class and do something with each KeyValuePair. 我需要从此静态类中检索所有静态属性,并对每个KeyValuePair做一些事情。 But the following throws a System.FormatException at runtime saying that it could not find recognizable digits 但是以下内容在运行时引发System.FormatException,表示找不到可识别的数字

Type type = typeof(Cars);
foreach(var manufacturer in type.GetProperties())
{
    if(manufacturer.PropertyType == typeof(KeyValuePair<Guid, string>))
    {
        var v = manufacturer.GetValue(null, null); //this does not work
        // How to get the KeyValuePair<Guid, string>? 
    }
}

How to get each KeyValuePair? 如何获得每个KeyValuePair?

UPDATE: Sorry.. the solution works perfectly, the problem is that GUID are not valuid Guids.. M is not hexadecimal character 更新:对不起..解决方案完美地工作,问题是GUID不是很重要的Guid .. M不是十六进制字符

This does not have to do anything with reflection or static properties. 这与反射或静态属性无关。 Within the getters of your properties there are exceptions thrown. 在属性的获取器中,抛出了异常。

"MMMMMMMM-509B-477A-ADB1-5CD014B41001" and "MMMMMMMM-509B-477A-ADB1-5CD014B41002" are no valid Guid s. "MMMMMMMM-509B-477A-ADB1-5CD014B41001""MMMMMMMM-509B-477A-ADB1-5CD014B41002"不是有效的Guid Create Guid s with valid values and the properties won't throw the exceptions. 使用有效值创建Guid ,属性不会引发异常。

Each of the digits in a Guid must be a hexadecimal digit (see here ). Guid每个数字都必须是一个十六进制数字(请参见此处 )。

new Guid("MMMMMMMM-509B-477A-ADB1-5CD014B41001")

will throw the exception, while for example 将抛出异常,例如

new Guid("00000000-509B-477A-ADB1-5CD014B41001")

won't. 惯于。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM