C# 接口中声明的方法的约束
有没有办法要求方法结果尊重某个属性? 比如C# 接口中声明的方法的约束,c#,.net,C#,.net,有没有办法要求方法结果尊重某个属性? 比如 我想在定义中强制执行这种请求。可能吗?不,不可能。合同根本没有定义这些类型的约束 在编译时检查接口约束,编译器通常无法知道函数的返回值。不幸的是,在c语言中使用接口是不可能的。您可以让接口的调用方强制执行此操作,或者改用抽象类: abstract class MybaseClass() { protected virtual int MyMethodInternal(int a, int b){ //this method is not vis
我想在定义中强制执行这种请求。可能吗?不,不可能。合同根本没有定义这些类型的约束
在编译时检查接口约束,编译器通常无法知道函数的返回值。不幸的是,在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!");
}
}
抽象类MybaseClass()
{
受保护的虚拟int-MyMethodInternal(int a,int b){//此方法对外不可见
//实现者覆盖了这一点
}
公共密封的int-MyMethod(inta,intb){//用户调用此方法
var res=MyMethodInternal(a,b);
如果(res<10)
抛出新异常(“错误的实现!”);
}
}
您可以定义一个小于10的数字的枚举。相关问题:@DarthVader一个枚举仍然有一个包含很多超过10个值的基础类型。您的第一句话可能暗示,在其他一些语言中,可以执行我需要的操作。这是真的吗?你能告诉我一些方向吗?你可以看看,但我认为它不支持接口上的前置/后置条件,只支持常规方法
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!");
}
}