问题描述
实际位置如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace cns01
{
class Program
{
public class datafieldInfo2<T>
{
public bool IsSearchValue { get; set; } = false;
public T Value { get; set; }
}
public class SmartRowVertrag
{
public datafieldInfo2<int> ID { get; set; }
public datafieldInfo2<string> VSNR { get; set; }
}
static void Main(string[] args)
{
SmartRowVertrag tester = new SmartRowVertrag();
tester.ID = new datafieldInfo2<int>() { Value = 777,IsSearchValue = false };
tester.VSNR = new datafieldInfo2<string>() { Value = "234234234",IsSearchValue = true };
var g = RetData3(tester);
}
public static object RetData3(object fsr)
{
object retVal = new object();
var props = fsr.GetType().GetProperties();
foreach (var prop in props)
{
PropertyInfo propInfo = prop.GetType().GetProperty("IsSearchValue"); // <-- here I get null
propInfo = prop.PropertyType.GetProperty("IsSearchValue"); // here I get a propertyInfo,but...
dynamic property = propInfo.GetValue(fsr,null); // ...<-- here fires error
var result = property.IsSearchValue;
if (result == true)
{
// doThis
}
}
return retVal;
}
}
}
我确实需要获取存储在IsSearchValue
中的布尔值才能完成任务。
谢谢。
我非常感谢有帮助的答案。
解决方法
fsr
是SmartRowVertrag
。您正在尝试从中获取IsSearchValue
-但它不存在。
相反,您需要调用GetValue
两次-在prop
上一次,传入fsr
(因此等效于使用fsr.ID
或{{1} }),然后在dsr.VSNR
上一次传递第一个调用的结果。
接下来,您使用propInfo
的目的是根据dynamic
的结果获取IsSearchValue
-您正在尝试有效地评估propInfo.GetValue()
。
以下是该部分的更正代码:
something.IsSearchValue.IsSearchValue
尽管您有public static object RetData3(object fsr)
{
object retVal = new object();
var props = fsr.GetType().GetProperties();
foreach (var prop in props)
{
PropertyInfo propInfo = prop.PropertyType.GetProperty("IsSearchValue");
if (propInfo != null)
{
object fieldInfo = prop.GetValue(fsr);
object isSearchValue = propInfo.GetValue(fieldInfo);
if (isSearchValue.Equals(true))
{
Console.WriteLine($"{prop.Name} has a searchable field");
}
}
}
return retVal;
}
实现的非通用接口或基类,也可以避免两次使用反射。例如:
DataFieldInfo2<T>
然后您可以使反射代码更清晰:
public interface IDataFieldInfo
{
bool IsSearchValue { get; }
}
public class DataFieldInfo2<T> : IDataFieldInfo
{
...
}