【发布时间】:2018-05-08 16:25:00
【问题描述】:
我找到了很多例子,几乎可以告诉我我需要知道什么。但到目前为止,一切都假设我已经有一个要设置值的属性实例。但是我没有实例。我有一个 PropertyInfo 对象。我可以动态获取属性的名称,但为了调用 SetValue(),我 必须 具有要传递给方法的属性的 instance。如何获取需要设置其值的属性实例?这是我的代码???必须提供属性实例的地方。如何获取属性的实例而不仅仅是 PropertyInfo 对象? (我之所以写这个方法是因为我不能保证各种存储过程会返回哪些列。)
protected new void MapDbResultToFields(DataRow row, DataColumnCollection columns)
{
Console.WriteLine("Entered Clinician.MapDbResultToFields");
var properties = this.GetType().GetProperties();
Console.WriteLine("Properties Count: " + properties.Length);
foreach (DataColumn col in columns)
{
Console.WriteLine("ColumnName: " + col.ColumnName);
}
foreach (var property in properties)
{
string propName = property.Name.ToLower();
Console.WriteLine("Property name: " + propName);
Console.WriteLine("Index of column name: " + columns.IndexOf(propName));
Console.WriteLine("column name exists: " + columns.Contains(propName));
if (columns.Contains(propName))
{
Console.WriteLine("PropertyType is: " + property.PropertyType);
switch (property.PropertyType.ToString())
{
case "System.String":
String val = row[propName].ToString();
Console.WriteLine("RowColumn Value (String): " + val);
property.SetValue(???, val, null);
break;
case "System.Nullable`1[System.Int64]":
case "System.Int64":
Int64.TryParse(row[propName].ToString(), out var id);
Console.WriteLine("RowColumn Value (Int64): " + id);
property.SetValue(???, id, null);
break;
case "System.Boolean":
Boolean.TryParse(row[propName].ToString(), out var flag);
Console.WriteLine("RowColumn Value (Boolean): " + flag);
property.SetValue(???, flag, null);
break;
}
}
else
{
Console.WriteLine("Property name not found in columns list");
}
}
}
【问题讨论】:
-
你需要一个对象的实例,而不是属性(属性没有实例)。
-
您正在获取
this的属性的 PropertyInfos。你还想要哪个实例? -
您是否要在
this上设置属性?如果是这样property.SetValue(this, val, null); -
很可能,您只需将
???更改为this。好吧,其他解决方案是在这里使用StackOverflowException的实例。 -
好吧,你们都知道,你是对的。对不起,我遇到了一个“笨蛋”的案例。当我将“this”作为对象传递时,这是有效的。这也是有道理的。
标签: c# reflection .net-core propertyinfo