是否有 C# 等价于 Python 的 __dict__
Is there a C# equivalent of Python's __dict__
当试图查看已实例化的给定 class 的所有实例属性时,我可以在 python:
中执行此操作
myObject.__dict__
查看为此实例存储的所有 key/value 对。
这可以用 C# 完成吗?
我不确定是否有任何方法可以专门做到这一点。但是,您可以 JSON 对对象进行编码并将其打印为某种类似的概念。
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsonSerializer.Serialize(yourDictionary);
//output json
让它做一个 "pretty print" 也可能是值得的,这样更容易阅读:
How do I get formatted JSON in .NET using C#?
这使用 JSON.net,但我还是更喜欢它:
string json = JsonConvert.SerializeObject(yourDictionary, Formatting.Indented);
Console.WriteLine(json);
不太重复,所以我不会这样标记它,但请看一下 How to get the list of properties of a class?。关于如何使用 Reflection
库,有一些很好的示例。例如,您可以使用 myObject.GetType().GetProperties()
。这只有 return 具有至少一个访问器(get
或 set
)的属性。因此,具有 public int num = 0
的实例不会包含在 return 中,但 public int num {get; set;} = 0
会包含。
反射库中的 Type.GetFields()
和 Type.GetField(string)
也可能接近您要查找的内容。例如:
Type t = typeof(myType);
FieldInfo[] arr = t.GetFields(BindingFlags.Public|BindingFligs.NonPublic);
var newInstance = new myType();
foreach (FieldInfo i in arr)
{
Console.WriteLine(i.GetValue(newInstance));
}
当试图查看已实例化的给定 class 的所有实例属性时,我可以在 python:
中执行此操作myObject.__dict__
查看为此实例存储的所有 key/value 对。
这可以用 C# 完成吗?
我不确定是否有任何方法可以专门做到这一点。但是,您可以 JSON 对对象进行编码并将其打印为某种类似的概念。
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsonSerializer.Serialize(yourDictionary);
//output json
让它做一个 "pretty print" 也可能是值得的,这样更容易阅读:
How do I get formatted JSON in .NET using C#?
这使用 JSON.net,但我还是更喜欢它:
string json = JsonConvert.SerializeObject(yourDictionary, Formatting.Indented);
Console.WriteLine(json);
不太重复,所以我不会这样标记它,但请看一下 How to get the list of properties of a class?。关于如何使用 Reflection
库,有一些很好的示例。例如,您可以使用 myObject.GetType().GetProperties()
。这只有 return 具有至少一个访问器(get
或 set
)的属性。因此,具有 public int num = 0
的实例不会包含在 return 中,但 public int num {get; set;} = 0
会包含。
Type.GetFields()
和 Type.GetField(string)
也可能接近您要查找的内容。例如:
Type t = typeof(myType);
FieldInfo[] arr = t.GetFields(BindingFlags.Public|BindingFligs.NonPublic);
var newInstance = new myType();
foreach (FieldInfo i in arr)
{
Console.WriteLine(i.GetValue(newInstance));
}