最好的“宏观方式”来重复C#行

时间:2012-08-11 18:40:10

标签: c# macros

在C#程序中,我有一个错误检查,重复了很多次:

try 
{
  File.Move(searchfolder + question1 +"_"+ filestring +".txt", 
            searchfolder + question1 +".txt");
}
catch (Exception ex) 
{
  File.AppendAllText(adminfolder + question1 +"_l.txt", "!"); 
  side.Value = Convert.ToString(ex) + "[Check-In error at "
                               + Convert.ToString(MYLINE) +"] "+ side.Value;
}

MYLINE是一个数字,MYLINE是我的程序中唯一改变的东西。

因此,正常的C ++ #define宏可以使这个更简单(我只需要在程序的顶部编写完整的“#define CHECKIN(MYLINE)...”)。

专业人士如何在C#中解决这个问题?

1 个答案:

答案 0 :(得分:5)

  

... MYLINE是我的计划中唯一改变的东西。因此,正常的C ++ #define宏可以使这更容易使用

好吧,也许,但是因为C#没有宏的概念......只需使用一种方法:

static class FileMover
{
    public static void MoveMyFile(string myline)
    {
        // your existing code here
    }
}

另外,您的代码中存在明显的问题。在catch块中,您调用File.AppendAllText() ...当然,也可以抛出异常。你需要考虑到这一点。