【发布时间】:2017-01-28 17:06:14
【问题描述】:
我正在编写代码以将我的 ORM 实体的数据传输到数据集中。因为我不想为定义需要写下哪些属性的每种类型编写特殊代码,所以我目前正在使用反射(在实体类型上调用 GetProperties,为此类型构建 DataTable,然后在每个 Propertyinfo 上调用 GetValue每个实体)。现状:可以,但是速度很慢。
现在我正在尝试构建一个方法,该方法返回一个函数以快速检索某些属性的值,但我在这里遇到了困难。这是我到目前为止得到的:
/// <summary>
/// creates a func that will return the value of the given property
/// </summary>
/// <typeparam name="T">type of the entity</typeparam>
/// <param name="propertyInfo">the property to get the value from</param>
/// <returns>a function accepting an instance of T and returning the value of the property</returns>
private Func<T, object> CreateGetPropertyFunc<T>(PropertyInfo propertyInfo)
{
MethodInfo getMethod = propertyInfo.GetGetMethod();
return (Func<T, object>)Delegate.CreateDelegate(typeof(Func<T, object>), getMethod);
}
这些是我的单元测试:
[TestMethod]
public void TestGenerateDelegate()
{
var employee = new Employee
{
Id = 1,
Name = "TestEmployee",
};
Func<Employee, object> getIdValueFunc = CreateGetPropertyFunc<Employee>(typeof(Employee).GetProperty("Id"));
Assert.AreEqual(1, getIdValueFunc(employee));
}
[TestMethod]
public void TestGenerateDelegateName()
{
var employee = new Employee
{
Name = "Test"
};
Func<Employee, object> getNameValueFunc = CreateGetPropertyFunc<Employee>(typeof(Employee).GetProperty("Name"));
Assert.AreEqual("Test", getNameValueFunc(employee));
}
当我调用第一个时,会引发 ArgumentException,其中包含消息“绑定到目标方法时出现异常”(已翻译,可能是不同的文本)。第二个测试反而通过了。
我很确定我没有正确处理 CreateDelegate 方法。谁能指点我正确的方向,好吗?
更新:
正如 PetSerAI 所说,这似乎是方差的问题,值原始类型不能通过 CreateDelegate 作为对象返回...
【问题讨论】:
-
委托返回类型差异不适用于值类型。您不能将返回
int的方法绑定到返回object的委托。 -
你是对的,它使用 Name 属性,但不适用于 Id。真可惜!
标签: c# reflection