C#泛型约束 [英] C# generic constraints
问题描述
是否有可能列举哪些类型是一个通用的限制可用
T的MyMethod< T>( )其中T:INT,双,字符串
为什么我要做到这一点的是,我有一个小评估引擎,并想为$像本b $ b写代码:
布尔expression.Evaluate<布尔>();
或
INT expression.Evaluate< INT>();
但我想禁止
MyCustomClass expression.Evalaute< MyCustomClass>();
这是不可能限制一个通用的参数来具体。类型
作为一种变通方法,您可以为每种类型的方法和转发方法调用一个共同的实现:
公共类表达{
公共BOOL EvaluateToBool(){
返回评估和LT;布尔>();
}
公众诠释EvaluateToInt32(){
返回评估和LT; INT>();
}
私人牛逼评价< T>(){
返回默认值(T);
}
}
在另一方面,你有没有想过在表达式类型的编码表达式计算的类型? 。例如
公共抽象类表达式来; T> {
公共抽象牛逼评估();
}
公共密封类AddExpression:表达式来; INT> this.Left = {左
{
公共AddExpression(右表达式来; INT>左,表达< INT>);
this.Right =权利;
}
公共表达式来; INT>左{搞定;私人集; }
公共表达式来; INT>右{搞定;私人集; }
公共覆盖INT评估(){
返回this.Left.Evaluate()+ this.Right.Evaluate();
}
}
Is it possible to enumerate which types that is "available" in a generic constraint?
T MyMethod<t>() where T : int, double, string
Why I want to do this is that I have a small evaluator engine and would like to write code like this:
bool expression.Evaluate<bool>();
or
int expression.Evaluate<int>();
but i want to prohibit
MyCustomClass expression.Evalaute<MyCustomClass>();
It is not possible to restrict a generic argument to specific types.
As a workaround, you could provide a method for each type and forward the method calls to a common implementation:
public class Expression {
public bool EvaluateToBool() {
return Evaluate<bool>();
}
public int EvaluateToInt32() {
return Evaluate<int>();
}
private T Evaluate<T>() {
return default(T);
}
}
On the other hand, have you thought about encoding the type the expression evaluates to in the Expression type? E.g.
public abstract class Expression<T> {
public abstract T Evaluate();
}
public sealed class AddExpression : Expression<int> {
public AddExpression(Expression<int> left, Expression<int> right) {
this.Left = left;
this.Right = right;
}
public Expression<int> Left { get; private set; }
public Expression<int> Right { get; private set; }
public override int Evaluate() {
return this.Left.Evaluate() + this.Right.Evaluate();
}
}
这篇关于C#泛型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!