为什么不能将运算符作为参数传递? [英] Why is it not possible to pass an operator as an argument?
问题描述
我试图编写一个具有LINQ查询的方法.
I was trying to write a method which has a LINQ query.
这种方法:
DoSomething(Operator operator, string name)
{
// if operator is ==
// use == as comparison
// if operator is !=
// use != as comparison
// pseudo query
var result = from rec in collection
where rec.name operator name
select rec;
}
我知道可以使用委托和Func and Action来完成此操作,并且对此进行了非常优雅的解释
I know this can be done using delegates and Func and Action and it was explained very elegantly here.
但是我想知道的是为什么一个方法只接受一个类型?为什么CLR不允许将运算符作为参数传递给方法?设计背后的想法是什么?
But what I wanted to know is why a method takes only a type? Why doesn't the CLR allow an operator to be passed as an argument to a method? What's the idea behind the design?
推荐答案
我要说的很简单,因为那不是操作符的处理方式.考虑一个这样的类:
I would say quite simply because that's just not how operators are handled. Consider a class like this:
public class A
{
public int Prop { get; set; }
}
,现在考虑以下代码:
var a1 = new A() { Prop = 1 };
var a2 = new A() { Prop = 2 };
此刻我需要这样做:
if (a1.Prop == a2.Prop)
这将起作用,但是如果我能做到这一点呢?
and that would work, but what if I could just do this:
if (a1 == a2)
的确意味着上述内容.这就是操作员的工作.这就是为什么您不能将它们作为参数传递的原因.实际上,我刚刚展示的代码比您提供的代码更简洁.为什么不这样重载运算符:
and that really meant the aforementioned. That's what operators do. That's why you can't pass them as parameters. In fact, the code I just showed is more concise than what you're offering. Why not just overload the operators like this:
public static bool operator ==(A a1, A a2)
{
return a1.Prop == a2.Prop;
}
,或者在您的情况下,在重载中运行适当的查询.就这么简单!
or in your case, run the appropriate query in the overload. Simple as that!
这篇关于为什么不能将运算符作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!