Translate code from Java to .NET
I need to translate this fragment from Java to .NET (rather C#, but I know Visual Basic too). This is code:
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 cat开发者_高级运维ch block
e.printStackTrace();
}
}
First line (Dictionary class) is from .NET (my translation try ;)). I know the Field class is from java.lang.reflect.Field, but I couldn't found .NET equivalent. Kind regards!
You're looking for the System.Reflection.FieldInfo
class and typeof(SomeType).GetFields()
.
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);
}
try to do this
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;
}
}
精彩评论