c# - 无法在 C# 项目中使用 GetValues 和 SetValues

标签 c#

我想将 DataRow 转换为对象。我写了 1 节课来做到这一点。 像这样的错误:

方法“SetValue”没有重载需要 2 个参数

方法“GetValue”没有重载需要 1 个参数

但我不能使用 GetValues() 和 SetValues()。将项目转换为 4.5 时。是工作。 我的项目设置平台目标为 3.5(强制性 - 因为我必须使用 .NET 3.5 连接设备)。

如何解决这个问题?

这是我的代码:

    public DataRowToObject(DataRow row)
    {
        List<PropertyInfo> listProperty = this.GetProperties();
        foreach (PropertyInfo prop in listProperty)
        {
            if (!row.Table.Columns.Contains(prop.Name) ||
                row[prop.Name] == null ||
                row[prop.Name] == DBNull.Value)
            {
                prop.SetValue(this, null);
                continue;
            }

            try
            {
                object value = Convert.ChangeType(row[prop.Name], prop.PropertyType);
                prop.SetValue(this, value);
            }
            catch
            {
                prop.SetValue(this, null);
            }
        }
    }
    public virtual Hashtable GetParameters()
    {
        Type type = this.GetType();
        List<PropertyInfo> listProperty = new List<PropertyInfo>(type.GetProperties());

        Hashtable result = new Hashtable();
        foreach (PropertyInfo prop in listProperty)
        {
            result.Add(prop.Name, prop.GetValue(this));
        }

        return result;
    }

最佳答案

PropertyInfo.SetValuePropertyInfo.GetValue 在 .NET 4.5 中没有添加索引器。

但这只是将 null 传递给以前版本的索引器参数的问题(使用 thisthis 重载)。

所以:

prop.SetValue(this, value, null);

prop.GetValue(this, null);

这应该适用于 .NET .3.5(最新版本)...实际上适用于 NET 2.0 及更高版本:-)

关于c# - 无法在 C# 项目中使用 GetValues 和 SetValues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34261518/

相关文章:

c# - WireMock.Net 如何响应有时错误和其他 OK

c# - 如何以编程方式(C# 或 Java)在 Windows 中启动应用程序并在其窗口中调用点击?

c# - 当你真的不能使用参数时如何为 SQL 查询转义字符串

c# - 如何调整 ListView 的高度以适应内容

c# - LINQ 首先选择

c# - Asp.Net - 使用 IHostedService 的计划任务

c# - 如何从 .NET 对象创建 XML 文档?

c# - 如何在 MS Access 中使用 C# 获取所有表名和列名?

c# - 编辑 XAML 导致 Visual Studio 的设计器崩溃

c# - 返回插入的 IDENT_CURRENT