不必要的变量分配

时间:2019-09-09 12:20:33

标签: c# variables try-catch

我对变量的不必要分配有疑问。

我有很多功能,其中一些功能在遇到异常时会将其写入日志文件中。

例如,这是其中之一(只需使用powershell重命名PC):

public static bool SetMachineName(string name)
{
        try
        {
            Runspace rs;
            rs = RunspaceFactory.CreateRunspace();
            rs.Open();

            using (PowerShell ps = PowerShell.Create())
            {
                ps.AddCommand("Rename-computer");
                ps.AddParameter("newname", name);
                ps.Runspace = rs;
                ps.Invoke();
                return true;
            }
        }
        catch (Exception ex)
        {
            LogWriter loger = new LogWriter(ex.ToString());
            return false;
        }
}

当我创建日志记录器以写入文件时,它说:“不必要地将值分配给'loger',但这仅在某些功能上起作用。

例如,我在此函数中未收到此错误:

public static bool VPNAdapterExists(string VPNAdapterName)
    {
        try
        {
            // VPN adapters are stored in the rasphone.pdk
            // "C:\Users\Me\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk"
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
                          @"\Microsoft\Network\Connections\Pbk\rasphone.pbk";

            const string pattern = @"\[(.*?)\]";
            var matches = Regex.Matches(File.ReadAllText(path), pattern)
                .OfType<Match>()
                .Select(m => m.Groups[0].Value)
                .ToArray();

            bool has = matches.Contains(VPNAdapterName);

            if (has == true) { return true; }
            else { return false; }

        }
        catch(Exception ex)
        {
            LogWriter loger = new LogWriter(ex.ToString());
            return false;
        }

    }

它只是一堆函数的类,有时我会收到此警告,有时却没有。而且只有在“捕获”块中,我才不会在“尝试”块中得到这个。

我不知道您是否也需要LogWriter类,所以这里是:

public class LogWriter
{
    private string m_exePath = string.Empty;
    public LogWriter(string logMessage)
    {
        LogWrite(logMessage);
    }
    public void LogWrite(string logMessage)
    {
        if (File.Exists("settings.xml"))
        {
            XmlSerializer xs = new XmlSerializer(typeof(Information));
            using (FileStream read = new FileStream("settings.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                Information info = (Information)xs.Deserialize(read);

                bool LogginEnabled;

                LogginEnabled = info.EnableLogging;
                if (LogginEnabled == true)
                {
                    m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    try
                    {
                        using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
                        {
                            Log(logMessage, w);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }

            }
        }
    }

    public void Log(string logMessage, TextWriter txtWriter)
    {
        try
        {
            txtWriter.Write("\r\n");
            txtWriter.Write("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            txtWriter.Write("  : {0}", logMessage);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

有人可以解释导致此问题的原因是什么,为什么如此随机?

感谢所有答案。

1 个答案:

答案 0 :(得分:3)

第一件事。

这里最大的问题是您在logger构造函数中记录了东西。那不是构造函数应该做的。构造函数必须正确构造一个对象以供以后使用。就是这样。

它应该像这样:

Logger logger = new Logger();
logger.WriteLog(ex.Message);

构造函数不应调用LogWrite。

因此,您收到的警告的意思是-“您将Logger分配给logger变量,但是您对该记录器对象却什么也没做。那么为什么要进行此分配?”

您还可以使其成为某种实用程序类:

static class Logger
{
    public static void WriteLog(string message)
    {
       //just write log here.
    }
}

然后您可以像这样使用它:

catch(Exception ex)
{
   Logger.WriteLog(ex.message);
}
相关问题