下面的例子编译成功。
编译器可以推断出 e (Customer) 的类型
我的问题是为什么 Intellisense 不能做同样的事情?
当我键入 customer.SetValue( 它正确地显示该方法期望
Expression<Func<Customer, TProperty>>
但是当我输入 e => e. 它无法理解 e 是一个客户
这是预期的还是错误?
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ConsoleApplicationExpressionTree
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.SetValue(e => e.Age, 10);
customer.SetValue(e => e.Name, "TheName");
//type here
}
}
public static class Extentions
{
public static void SetValue<TEntity, TProperty>(this TEntity instance, Expression<Func<TEntity, TProperty>> expression, TProperty newValue)
{
if (instance == null)
throw new ArgumentNullException();
var memberExpression = (MemberExpression)expression.Body;
var property = (PropertyInfo)memberExpression.Member;
property.SetValue(instance, newValue, null);
}
}
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
}
我正在使用 VS 2015,.NET 4.6.1
更新
跟Expression<>无关,方法可以改成
public static void SetValue<TEntity, TProperty>(this TEntity instance, Func<TEntity, TProperty> expression, TProperty newValue)
更新 2
我可以重现它
- VS 2015 企业
- VS 2015 社区版
它似乎可以在(尚未测试其他版本)
- VS 2013 终极版
- VS 2013 高级版
最佳答案
我已经在 connect.microsoft.com 提交了错误报告
关于c# - Intellisense 无法从扩展方法推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883559/