【问题标题】:Intellisense cannot infer type from extension methodIntellisense 无法从扩展方法推断类型
【发布时间】:2019-07-09 21:09:50
【问题描述】:

下面的例子编译成功。
编译器可以推断 e 的类型(客户)
我的问题是为什么 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 高级版

【问题讨论】:

  • 我已经发生过几次这种情况,大约每隔一周一次。关闭和重新打开 VS 通常会为我修复它,但它仍然很烦人。
  • 我确定已经省略了一些代码以保持问题较小,但我可以问一下扩展的目的来设置属性吗?
  • 看起来像一个错误,可能与 Roslyn 有关。
  • @Wobbles,不,这是完整的例子
  • @JRLambert 我已经重新启动了我的 VS/PC,但我总是遇到这个问题。我会打开一个错误报告

标签: c# .net visual-studio intellisense


【解决方案1】:

我已在 connect.microsoft.com 提交错误报告

【讨论】:

    【解决方案2】:

    这是预期的还是错误?

    两者都不是。

    虽然 Intellisense 可以尽可能地帮助您,但它从未声称可以正确解析代码中的每一个声明。传统上,这在 C++ 及其复杂的基于宏的声明中更多是一个问题,但你也会时不时地在 C# 中遇到问题。

    如果您愿意,您可以为此打开一个 Connect 问题,但除此之外,您可以轻松地接受它,所以不要期望响应太快(想想 2017 年而不是 2015 年更新 2)。

    【讨论】:

    • 感谢@Blindy 的回答,但由于它在以前的版本中有效,我认为这是一个错误
    猜你喜欢
    • 2011-11-15
    • 1970-01-01
    • 2011-04-07
    • 2021-11-19
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多