我已经找到了一个解决方案,但它似乎不适合我((CrazyCasta回答):
如何通过反射在单个调用中获得字段和属性?
正如我之前所说的,我使用了CrazyCasta的代码:
interface IGetSettable
{
public void SetValue(
Object obj,
Object value,
Object[] index);
public Object GetValue(
Object obj,
Object[] index);
}
public class ParameterInfoGS : IGetSettable
{
protected ParameterInfo pi;
public ParameterInfoExtra(ParameterInfo _pi)
{
pi = _pi;
}
public void SetValue(
Object obj,
Object value,
Object[] index) { pi.SetValue(obj, value, index); }
public Object GetValue(
Object obj,
Object[] index) { return pi.GetValue(obj, index); }
}
public class FieldInfoGS : IGetSettable
{
protected FieldInfo pi;
public FieldInfoExtra(FieldInfo _pi)
{
pi = _pi;
}
public void SetValue(
Object obj,
Object value,
Object[] index) {pi.SetValue(obj, value, index);}
public Object GetValue(
Object obj,
Object[] index) {return pi.GetValue(obj, index);}
}
public static class AssemblyExtension
{
public static IGetSettable[] GetParametersAndFields(this Type t)
{
List<IGetSettable> retList = new List<IGetSettable>();
foreach(ParameterInfo pi in t.GetParameters())
retList.Add(new ParameterInfoExtra(pi));
foreach(FieldInfo fi in t.GetFields())
retList.Add(new FieldInfoExtra(fi));
return retList.ToArray();
}
}
我得到了一些错误,如ParameterInfo不包含任何GetValue SetValue方法
我在之前的一个项目中做过类似的事情。看那个
IEnumerable<PropertyInfo> props = from n in typeof(MyClass).GetProperties()
let get = n.GetGetMethod()
let set = n.GetSetMethod()
where get != null && set != null &&
n.DeclaringType == typeof(MyClass)
select n;
foreach (PropertyInfo info in props)
{
// Code goes here. Something like:
object obj = info.GetValue(instanceOfMyClass);
}
但最终我摆脱了这段代码,因为这是一个糟糕的方法;)