当前位置: 首页 > 编程语言 > C#

C#-Delegatewithanynumberofcustomparameters分享

时间:2023-04-10 16:21:13 C#

C#-Delegatewithanynumberofcustomparameters.我的意思是,我想推出具有不同返回类型和不同参数的不同方法。例如:publicdoubleSum(doublea,doubleb){returna+b;}publiccharGetFirst(stringa){returna[0];}publicboolcanFlipTable(object[]thingsOnIt){returnthingsOnIt.Length<=3;}DoTheThingthing1=newDoTheThing(Sum);DoTheThingthing2=newDoTheThing(GetFirst);DoTheThingthing3=newDoTheThing(canFlipTable);thing1.Call(10.3,5.6);//15.9thing2.Call("HelloWorld");//'H'thing3.Call(newobject[]{newLamp(),newLaptop(),newCoffeMug()});//true我已经计算出返回值并调用该方法,但我正在存储我的方法有问题如果我使用“publicDoTheThing(Actionmethod)”它说,参数不匹配我什至尝试使用“paramsobject[]p”作为参数的委托,但它也不起作用编辑:我忘了告诉,该方法将始终具有返回类型和至少1个参数编辑2:我的目标是创建一个包装类缓存非常昂贵的方法的输出,如果再次调用相同的东西,它将返回缓存的值。当然我可以用一个接口来解决这个问题,但是我想用不容易编辑的类来解决这个问题,我想让它变得灵活,所以把缓存放在我调用方法的同一个地方不是一个选项。我的代码是:publicclassDoTheThing{publicdelegateTMethod(paramsobject[]parameters);功能方法;ParameterInfo[]pInfo;publicDoTheThing(Method方法){this.method=方法;类型type=typeof(方法);MethodInfoinfo=type.GetMethod("调用");if(info.ReturnType!=typeof(T)){thrownewException("DoTheThing的类型和方法不匹配");}pInfo=info.GetParameters();}publicTCall(paramsobject[]parameters){if(parameters.Length!=pInfo.Length){thrownewException("Wrongnumberofarguments,"+parameters.Length+"而不是"+pInfo.Length);返回默认值(T);}for(inti=0;i{return$"将是{s},{i}次";});ret=mydel.DynamicInvoke("你好",5);System.Console.WriteLine(ret);因为“mydel”变量是基类类型(MulticastDelegate),我们实际上可以将它与任何类型的委托一起使用,并使用任意参数调用它。如果它们与被调用的方法不匹配,它将在运行时抛出。以上就是C#学习教程的全部内容:C#——使用任意数量的自定义参数进行委托和共享。代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: