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

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

例如,这就是其中之一(只需使用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;
        }
}


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

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

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;
        }

    }


它只是一堆函数的类,有时我会收到此警告,有时却不。而且仅在“ Catch”块中,即时消息无法在“ Try”块中获得。

我不知道您是否也需要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());
        }
    }
}



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

感谢所有答案。

最佳答案

首先是第一件事。

这里最大的问题是您在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);
}

10-04 12:34
查看更多