参数操作&LT; T1,T2,T3&GT;其中T3可选配 [英] Parameter Action<T1, T2, T3> in which T3 can be optional
问题描述
我有以下的code:
public static MyMethod()
{
...Do something
ProtectedMethod(param1, param2);
...Do something
}
protected static void ProtectedMethod(IEnumerable<string> param1, string param2, int param3 = 1)
{
... Do something
}
以可选参数3参数的通知。
现在对于相当多的原因,我需要提取的MyMethod方法的code到它自己的类,但我不能,因为一切都从这一个继承的类提取ProtectedMethod,我需要保持改变小型和孤立的。所以,我想我可以有一个动作&LT;>委托在新的类具有相同签名的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;
,因为它说的方法只被调用带两个参数的提取code不喜欢它。
The extracted code does not like it because it says the method is only being invoked with two parameters.
如果我宣布委托像这样:
And if I declare the delegate like so:
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.
这是唯一的选择,或者是有这样做,因为现在pferred选择了$ P $是有可选参数,而不是重载方法的另一种方式?
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);
在调用此委托时,你就可以省略第三个参数,不论何种方法(S)的声明中包含
When calling this delegate, you will be able to omit the third parameter, regardless of the declaration of the method(s) it contains.
这篇关于参数操作&LT; T1,T2,T3&GT;其中T3可选配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!