c# - 使用反射将通用类字段解析器转换为 Dictionary<String, String>

标签 c# .net reflection

我很多次考虑将类的示例转换为 Dictionary<String, String>其中 key 是变量名称(类字段名称),value 是变量当前分配的值。所以我们有一个简单的类:

public class Student
{
    public String field1;
    public Int64 field2;
    public Double field3;
    public Decimal field4;

    public String SomeClassMethod1()
    {
        ...
    }
    public Boolean SomeClassMethod2()
    {
        ...
    }
    public Int64 SomeClassMethod1()
    {
        ...
    }
}

我期望它会是什么样子:

static void Main(String[] args)
{
    Student student = new Student(){field1 = "", field2 = 3, field3 = 3.0, field4 = 4.55m};
    Dictionary<String, String> studentInDictionary = ConvertAnyToDictionary<Student>(student);
}

public Dictionary<String, String> ConvertAnyToDictionary<T>(T value) where T:class
{
...
}

关于如何实现它有什么想法吗?非常感谢您的任何建议。

编辑1: 预期结果:

studentInDictionary[0] = KeyValuePair("field1", "");
studentInDictionary[1] = KeyValuePair("field2", (3).ToString());
studentInDictionary[2] = KeyValuePair("field3", (3.0).ToString());
studentInDictionary[3] = KeyValuePair("field4", (4.55m).ToString());

最佳答案

以下是具体操作方法:

public static Dictionary<String, String> ConvertAnyToDictionary<T>(T value) where T : class {
    var fields = typeof(T).GetFields();
    var properties = typeof(T).GetProperties();

    var dict1 = fields.ToDictionary(x => x.Name, x => x.GetValue(value).ToString());
    var dict2 = properties.ToDictionary(x => x.Name, x => x.GetValue(value, null).ToString());

    return dict1.Union(dict2).ToDictionary(x => x.Key, x=> x.Value);
}

编辑:我正在计算其中的字段属性。如果您只使用属性,则可以使用 dict2

您可能想查看 GetFields()GetProperties() 方法接收的 BindingFlags 参数。

关于c# - 使用反射将通用类字段解析器转换为 Dictionary<String, String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15107909/

相关文章:

.net - AppDomains 和 GC 堆

c# - 在 C# .NET 中,如何在不引发错误的情况下从线程内设置组件属性?

java - 创建类型 X 的通用字段并通过反射将其值设置为(不相关的)类型 Y 不会导致 IllegalArgumentException

java - GWTTestCase:测试私有(private)方法

c# - VisualStateManager 是否支持数据绑定(bind)或模板绑定(bind)?

c# - 我应该为模块化创建 DLL 吗?

c# - C# 的检查样式?

.net - 在 .NET 中快速搜索 XMl 文件(或如何索引 XML 文件)

java - 为什么我的反射加载奇怪的类?

c# - 为什么 postsharp 导致 web 项目发布失败?