获取类中所有变量名字,以及变量类型,并且根据类型调用相应的方法
时间: 2024-01-17 11:05:43 浏览: 31
可以通过反射获取类中所有的字段(包括私有、公有字段),并获取它们的名称和类型,然后根据类型调用相应的方法。具体代码如下:
```csharp
using System;
using System.Reflection;
public class MyClass
{
private int privateField;
public string publicField;
}
class Program
{
static void Main(string[] args)
{
MyClass myObject = new MyClass();
Type type = myObject.GetType();
FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
Console.WriteLine("Field Name: {0}, Field Type: {1}", field.Name, field.FieldType);
if (field.FieldType == typeof(int))
{
int value = (int)field.GetValue(myObject);
Console.WriteLine("Integer Value: {0}", value);
}
else if (field.FieldType == typeof(string))
{
string value = (string)field.GetValue(myObject);
Console.WriteLine("String Value: {0}", value);
}
// add more else-if statements here for other types
}
Console.ReadKey();
}
}
```
上述代码中,首先创建了 `MyClass` 类的一个实例 `myObject`,然后使用 `GetType` 方法获取该实例的类型。接着使用 `GetFields` 方法获取该类型中的所有字段。遍历 `fields` 数组,获取每个字段的名称和类型,如果字段的类型是 `int` 类型,则调用 `GetValue` 方法获取该字段的值,并输出该值;如果字段的类型是 `string` 类型,则同样调用 `GetValue` 方法获取该字段的值,并输出该值。可以根据需要添加更多的类型判断和对应的操作。
输出结果为:
```
Field Name: privateField, Field Type: System.Int32
Integer Value: 0
Field Name: publicField, Field Type: System.String
String Value:
```
其中,`privateField` 字段是私有字段,类型为 `int`,值为 `0`;`publicField` 字段是公有字段,类型为 `string`,值为空字符串。输出结果中可以看到它们的名称、类型和值。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)