c# - 可以通过索引方式获取类属性值或如何摆脱辅助方法 'GetValue'

标签 c#

我有以下代码,

var data = new Dictionary<string, TestData>
            {
                { "A1", new TestData { Name = "N1", Section = "S1" } },
                { "A2", new TestData { Name = "N2", Section = "S2" } }
            };

            var strArray = new string[2] { "Name", "Section" };

            foreach (KeyValuePair<string, TestData> entry in data)
            {
                foreach (string value in strArray)
                {
                    var X = GetValue(value, entry.Value);
                }
            }

private static string GetValue(string value, TestData data)
    {
        string val = string.Empty;

        if(value == "Name")
        {
            val = data.Name;
        }

        if (value == "Section")
        {
            val = data.Section;
        }

        return val;
    }

这里类属性和字符串数组具有相同的名称NameSection,我使用小辅助方法来获取类属性值GetValue(value,entry .值).

问题,有没有办法摆脱辅助方法 GetValue 或类似索引的任何方式,var X = entry.Value[value];

最佳答案

这里有两种方法可以直接添加到类中或者需要使用扩展方法。

我应该提到,如果您的字符串不是属性,这只会引发异常。您需要做一些检查。

public class TestData
{
    public string Name { get; set; }
    public string Section { get; set; }

    public string Value(string value)
    {
        var val = typeof(TestData).GetProperty(value).GetValue(this);

        // This will return null instead of throwing an exception
        // var val = typeof(TestData).GetProperty(value)?.GetValue(this);

        if (val is string result)
        {
            return result;
        }

        return default;
    }
}

或者使用扩展方法

public static class TestDataExtensions
{
    public static string Value(this TestData testData, string value)
    {
        var val = typeof(TestData).GetProperty(value).GetValue(testData);

        if (val is string result)
        {
            return result;
        }

        return default;
    }
}

关于c# - 可以通过索引方式获取类属性值或如何摆脱辅助方法 'GetValue',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55217561/

相关文章:

c# - 如何通过部分名称查找文件夹和文件 C#

c# - 在asp.net C#中动态捕获特定url的图像

c# - 列表内列表,我想在 c# Linq 或 Lambda 中对内部列表项进行分页

c# - LINQPAD 5 中的日期时间和 GroupBy 与 MySQL

C# - 如何获取 oracle long 原始类型值

c# 自定义表达式变量(因为我没有更好的术语)

c# - 如何通过将 dll 导入引用来在 C#.net for winforms 的工具箱中添加用户控件?

c# - 自定义 http 服务可以很好地响应本地 IP 地址,但不能响应 localhost 或 127.0.0.1

c# - Entity Framework 6 和 .NET Core 应用程序

c# - 如何删除一个表