问题描述
我有以下代码:
public static MyMethod()
{
...Do something
ProtectedMethod(param1, param2);
...Do something
}
protected static void ProtectedMethod(IEnumerable<string> param1, string param2, int param3 = 1)
{
... Do something
}
注意可选的 param3 参数.
现在由于很多原因,我需要将 MyMethod 方法的代码提取到它自己的类中,但我不能用它提取 ProtectedMethod,因为所有类都继承自这个类,我需要保持较小的更改并且孤立.所以我想我可以在新类中有一个 Action<> 委托,其签名与 ProtectedMethod 相同.
Now for quite a few reasons I need to extract the code of the MyMethod method into its own class but I cannot extract ProtectedMethod with it because of all the classes that are inheriting from this one and I need to keep the changes small and isolated. So I figured I could have an Action<> delegate in the new class with the same signature as ProtectedMethod.
问题是,如果我这样声明委托:
The problem is that if I declare the delegate like this:
protected readonly Action<IEnumerable<string>, string, int> m_ProtectedMethod;
提取的代码不喜欢它,因为它说该方法只被两个参数调用.
The extracted code does not like it because it says the method is only being invoked with two parameters.
如果我这样声明委托:
protected readonly Action<IEnumerable<string>, string> m_ProtectedMethod;
当我将它作为参数发送给新类时,它也不喜欢它,因为该方法被定义为具有三个参数而不是两个.
When I send it as a parameter to the new class it does not like it either because the method is defined as having three parameters not two.
到目前为止,我想到的解决此问题的唯一方法是创建 ProtectedMethod 的重载版本以消除可选参数.
So far the only way I have thought of to solve this is to create an overloaded version of ProtectedMethod to eliminate the optional parameter.
这是唯一的选择还是有另一种方法,因为现在首选的选择是使用可选参数而不是重载方法?
Is this the only option or is there another way of doing it since now the preferred choice is to have optional parameters instead of overloaded methods?
推荐答案
可选参数是方法或委托参数的属性.当您在编译时调用具有已知可选参数的签名(方法或委托)时,编译器将在调用点插入可选参数值.
Optional parameters are an attribute of a method or delegate parameter. When you call a signature (method or delegate) that has a known optional parameter at compile-time, the compiler will insert the optional parameter value at the callsite.
运行时不知道可选参数,因此您不能创建一个在调用时插入可选参数的委托.
The runtime is not aware of optional parameters, so you can't make a delegate that inserts an optional parameter when it's called.
相反,您需要使用可选参数声明自定义委托类型:
Instead, you need to declare a custom delegate type with an optional parameter:
public delegate void MyDelegate(IEnumerable<string> param1, string param2, int param3 = 1);
调用此委托时,您可以省略第三个参数,而不管它包含的方法的声明.
When calling this delegate, you will be able to omit the third parameter, regardless of the declaration of the method(s) it contains.
这篇关于参数动作<T1,T2,T3>其中 T3 可以是可选的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!