ReSharper警告我可能的NullReferenceException
WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);
我查看了MSDN文档,但没有看到任何提及.此外,它没有意义,因为如果您运行可执行文件,则必须先登录.
这只是一个ReSharper搜索模式吗?
使用ILSpy,您可以查看GetCurrent和GetCurrentInternal的解编译版本,GetCurrent调用GetCurrentInternal.
结果是:
原文链接:https://www.f2er.com/windows/371051.html结果是:
GetCurrent:
public static WindowsIdentity GetCurrent() { return WindowsIdentity.GetCurrentInternal(TokenAccessLevels.MaximumAllowed,false); }
GetCurrentInternal:
internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess,bool threadOnly) { int errorCode = 0; bool flag; SafeTokenHandle currentToken = WindowsIdentity.GetCurrentToken(desiredAccess,threadOnly,out flag,out errorCode); if (currentToken != null && !currentToken.IsInvalid) { WindowsIdentity windowsIdentity = new WindowsIdentity(); windowsIdentity.m_safeTokenHandle.Dispose(); windowsIdentity.m_safeTokenHandle = currentToken; return windowsIdentity; } if (threadOnly && !flag) { return null; } throw new SecurityException(Win32Native.GetMessage(errorCode)); }
因为从GetCurrent调用时ThreadOnly总是为false,而且currentToken必须对另一个return语句有效,我不认为你有获得一个空的WindowsIdentity的风险.