代码之家  ›  专栏  ›  技术社区  ›  Dave Cousineau

请求表达式<Func<T,decimal>>

c#
  •  0
  • Dave Cousineau  · 技术社区  · 5 年前

    所以, int 隐式转换为 decimal Expression 十进制的 财产,其中 表达式 一个 而是传递具有隐式转换的属性。由于隐式转换,因此不会给出编译器错误。

    如:

    class Thing {
       public int IntProperty { get; set; }
    }
    
    void DoSomething(
       Expression<Func<Thing, decimal>> pDecimalExpression
    ) {
       ...
    }
    
    DoSomething(t => t.IntProperty); // compiles; IntProperty is implicitly cast to decimal
    

    十进制的

    (因为我使用的是反射,所以我最后得到一个运行时错误,说我使用的属性不能被赋予 十进制的 价值观。我觉得我能做的最好的就是自己在运行时检测到类型不匹配,然后抛出一个稍微好一点的错误。)

    0 回复  |  直到 5 年前
        1
  •  5
  •   dropoutcoder    5 年前

    IEquatable<T> 限制可以传递的内容 T (内置类型实现此接口)。缺点是任何实现 IEquatable<decimal> 将被允许 泛型参数(在您的情况下可能是问题,也可能不是问题)。

    void DoSomething<T>(Expression<Func<Thing, T>> pDecimalExpression)
        where T : struct, IEquatable<decimal> {
        ...
    }
    

    希望有帮助。

        2
  •  3
  •   Ondrej Tucny    5 年前

    有个窍门你可以用。编译器将倾向于使用 int ObsoleteAttribute 's 发出编译时错误的能力。

    宣布 DoSomething 这样地:

    void DoSomething(Expression<Func<Thing, decimal>> pDecimalExpression)
    {
        // …
    }
    
    [Obsolete("No, no, no!", true)] // the true here causes an error instead of a warning
    void DoSomething(Expression<Func<Thing, int>> pIntExpression)
    {
        // just in case someone would call this method via reflection
        throw new NotSupportedException();
    }
    

    DoSomething(t => t.IntProperty);