我想将 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.SetValue
和 PropertyInfo.GetValue
在 .NET 4.5 中没有添加索引器。
但这只是将 null
传递给以前版本的索引器参数的问题(使用 this 和 this 重载)。
所以:
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/