是否可以将其重构为单一方法

sco*_*ott 6 c#

我有一堆看起来像这两个的方法:

   public void SourceInfo_Get()    
   {
        MethodInfo mi = pFBlock.SourceInfo.GetType().GetMethod("SendGet");
        if (mi != null)
        {
            ParameterInfo[] piArr = mi.GetParameters();
            if (piArr.Length == 0)
            {
                mi.Invoke(pFBlock.SourceInfo, new object[0]);
            }
        }
    }
    public void SourceAvailable_Get()
    {
        MethodInfo mi = pFBlock.SourceAvailable.GetType().GetMethod("SendGet");
        if (mi != null)
        {
            ParameterInfo[] piArr = mi.GetParameters();
            if (piArr.Length == 0)
            {
                mi.Invoke(pFBlock.SourceAvailable, new object[0]);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的pFBlock对象中的每个属性都有一个方法.在方法之间变化如此之少,我觉得应该有更好的方法来做到这一点,但我想不出任何方法.我正在使用VS 2005.

jjn*_*guy 7

3种方法怎么样?

public void SourceInfo_Get()    
{
    SendGet(pFBlock.SourceInfo);
}

public void SourceAvailable_Get()
{
    SendGet(pFBlock.SourceAvailable);
}

private void SendGet(Object obj) {
    MethodInfo mi = obj.GetType().GetMethod("SendGet");
    if (mi != null)
    {
        ParameterInfo[] piArr = mi.GetParameters();
        if (piArr.Length == 0)
        {
            mi.Invoke(obj, new object[0]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的想法是添加一个可以将参数传递给的辅助方法.然后,您可以在其他方法中使用辅助方法来大幅缩短代码.