C#:隐含运算符和扩展方法 [英] C#: implicit operator and extension methods
问题描述
我想创建一个 PredicateBuilder< T>
类包装了一个表达式来; Func键< T,BOOL>>
并提供了一些方法,可以轻松地建立各种和
和或者
方法的表达式。我认为这将是冷静,如果我可以用这个 PredicateBuilder< T>
为表达式来; Func键< T,BOOL>>
直接,认为这可以由具有隐含的运营商
的方法做事情。
I am trying to create a PredicateBuilder<T>
class which wraps an Expression<Func<T, bool>>
and provides some methods to easily build up an expression with various And
and Or
methods. I thought it would be cool if I could use this PredicateBuilder<T>
as an Expression<Func<T, bool>>
directly, and thought this could be done by having an implicit operator
method thing.
简化版的类看起来是这样的:
Stripped down version of the class looks like this:
class PredicateBuilder<T>
{
public Expression<Func<T, bool>> Predicate { get; protected set; }
public PredicateBuilder(bool initialPredicate)
{
Predicate = initialPredicate
? (Expression<Func<T, bool>>) (x => true)
: x => false;
}
public static implicit operator Expression<Func<T, bool>>(
PredicateBuilder<T> expressionBuilder)
{
return expressionBuilder.Predicate;
}
}
然后,就像一个测试,我有这个延伸方法在静态类:
Then, just as a test, I have this extention method in a static class:
public static void PrintExpression<T>(this Expression<Func<T, bool>> expression)
{
Console.WriteLine(expression);
}
在我的头上,我应该再能够做到这些:
In my head, I should then be able to do these:
var p = new PredicateBuilder<int>(true);
p.PrintExpression();
PredicateExtensions.PrintExpression(p);
但他们没有工作。对于第一个,扩展方法是找不到的。而对于第二个,它说,
However none of them work. For the first one, the extension method is not found. And for the second, it says that
的类型参数的方法ExtravagantExpressions.PredicateHelper.PrintExpression(System.Linq.Expressions.Expression> )'不能从使用推断。 。尝试显式指定类型参数
The type arguments for method 'ExtravagantExpressions.PredicateHelper.PrintExpression(System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
所以我尝试以下,这工作:
So I tried the following, which worked:
PredicateExtensions.PrintExpression<int>(p);
此外,这部作品,当然:
Also, this works, of course:
((Expression<Func<int, bool>>) p).PrintExpression();
但是,是的......为什么不别人打工?我误解了一些关于如何隐含的运营商
东西的作品?
推荐答案
这不是特定于扩展方法。 C#不会隐式转换一个对象为另一种类型,除非有关于目标类型的线索。假设如下:
This is not specific to extension methods. C# won't implicitly cast an object to another type unless there is a clue about the target type. Assume the following:
class A {
public static implicit operator B(A obj) { ... }
public static implicit operator C(A obj) { ... }
}
class B {
public void Foo() { ... }
}
class C {
public void Foo() { ... }
}
您期望哪种方法在下面的语句?
Which method would you expect to be called in the following statement?
new A().Foo(); // B.Foo? C.Foo?
这篇关于C#:隐含运算符和扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!