Parameter Action in which T3 can be optional

后端 未结 3 608
再見小時候
再見小時候 2020-11-30 08:52

I have the following code:

public static MyMethod()  
{ 
   ...Do something  
   ProtectedMethod(param1, param2);  
   ...Do something  
}  

protected stati         


        
3条回答
  •  青春惊慌失措
    2020-11-30 09:17

    It would depend on how m_ProtectedMethod would be consumed, but I found a compromise in my own situation, where I use one overload more than the other.

    Simply define a simpler (having less generic parameters) Action<> variable, which calls the more complex supplied Action variable method. This can be accomplished either in (i) local scope on use; or (ii) object scope upon assignment of Action property or object construction.

    Because there is no such thing as variable/property overloading, you need two different names, for the resulting two related Action variables.

    EG i: Local Scope (probably not the most suitable for your scenario)

    public MyMethod(Action, string, int> m_ProtectedMethod2)  
    { 
       Action, string> m_ProtectedMethod = (p1,p2) => {
          m_ProtectedMethod2(p1,p2,1); //The value 1 is the default 3rd parameter
       }
    
       ...Do something  
       m_ProtectedMethod(param1, param2);  
       ...Do something  
       ...If something  
          m_ProtectedMethod2(param1, param2, param3); //Calling the more complex form directly
       ...Do something  
    }  
    

    EG ii: Object Scope

    private Action, string, int> m_ProtectedMethod2 = null;
    private Action, string> m_ProtectedMethod = null;
    protected Action, string, int> ProtectedMethod
    {
       get { return m_ProtectedMethod2; }
       set {
          m_ProtectedMethod2 = value;
          m_ProtectedMethod = (p1,p2) => {
             m_ProtectedMethod2(p1,p2,1); //The value 1 is the default 3rd parameter
          }
       }
    }
    
    public MyMethod()
    {
       ...Do something  
       m_ProtectedMethod(param1, param2);  
       ...Do something  
       ...If something  
          m_ProtectedMethod2(param1, param2, param3); //Calling the more complex form directly
       ...Do something  
    }
    

    Note in both cases I designed the default setting value to be the more awkwardly named variable, having the 2 suffix, such that upon consumption the simpler overload has the more basic variable name.

提交回复
热议问题