有没有办法要求方法结果尊重某个属性?如
interface MyInterface()
{
int MyMethod(int a, int b);
// i want that my int result is less then 10
}
我想在定义中强制执行这种请求。可能吗?
不幸的是,在 c# 中使用接口是不可能的。您可以让接口的调用者强制执行此操作,或者使用抽象类代替:
abstract class MybaseClass()
{
protected virtual int MyMethodInternal(int a, int b){ //this method is not visible to the outside
// implementors override this
}
public sealed int MyMethod(int a, int b){ // users call this method
var res = MyMethodInternal(a,b);
if(res < 10)
throw new Exception("bad implementation!");
}
}
不,那是不可能的。合同根本没有定义这些类型的约束。
在编译时检查接口约束,编译器通常无法知道函数的返回值。