1

我需要将此片段从 Java 转换为 .NET(更确切地说是 C#,但我也知道 Visual Basic)。这是代码:

typeStrings = new Dictionary<Int16, String>();

    Field[] fields = Type.class.getDeclaredFields();

    for (Field field : fields) {
        try {
            typeStrings.put(field.getInt(null), field.getName());
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
    }

第一行(字典类)来自.NET(我的翻译尝试;))。我知道 Field 类来自 java.lang.reflect.Field,但我找不到 .NET 等价物。亲切的问候!

4

3 回答 3

7

您正在寻找System.Reflection.FieldInfo课程和typeof(SomeType).GetFields().

于 2011-05-31T12:19:00.763 回答
2
var typeStrings = new Dictionary<int, string>();

FieldInfo[] fields = yourObject.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (var field in fields)
{
    typeStrings.Add((int)field.GetValue(yourObject), field.Name);
}
于 2011-05-31T12:27:58.990 回答
1

尝试这样做

    var typeStrings = new Dictionary<Int16, String>();

    var fields = this.GetType().GetFields();

    foreach (var field in fields)
    {
        try
        {
            typeStrings.Add(Convert.ToInt16(field.FieldHandle.Value.ToInt32().ToString()), field.Name);
        }
        catch (Exception)
        {
            throw;
        }
    }
于 2011-05-31T12:38:13.220 回答