c# 写一个方法 参数是type 返回一个字典key string value type 里面的值是当前对象所有字段的名称以及类型
可以使用反射来实现这个方法。下面是一个示例代码:
using System;
using System.Collections.Generic;
using System.Reflection;
public class MyClass
{
public int MyInt { get; set; }
public string MyString { get; set; }
public bool MyBool { get; set; }
}
public static class ReflectionHelper
{
public static Dictionary<string, Type> GetFields(Type type)
{
Dictionary<string, Type> fields = new Dictionary<string, Type>();
FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo fieldInfo in fieldInfos)
{
fields.Add(fieldInfo.Name, fieldInfo.FieldType);
}
PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo propertyInfo in propertyInfos)
{
fields.Add(propertyInfo.Name, propertyInfo.PropertyType);
}
return fields;
}
}
public class Program
{
public static void Main(string[] args)
{
Type type = typeof(MyClass);
Dictionary<string, Type> fields = ReflectionHelper.GetFields(type);
foreach (KeyValuePair<string, Type> field in fields)
{
Console.WriteLine("Field Name: " + field.Key + ", Field Type: " + field.Value);
}
}
}
在上面的示例中,我们定义了一个 MyClass 类,该类具有三个属性:MyInt,MyString 和 MyBool。然后,我们编写了一个静态方法 GetFields,该方法使用反射获取给定类型的字段和属性,并将它们存储在字典中。最后,在 Main 方法中调用 GetFields 方法,并遍历字典以打印字段名称和类型
原文地址: http://www.cveoy.top/t/topic/iMLu 著作权归作者所有。请勿转载和采集!