问题描述
ReSharper警告我可能存在的NullReferenceException
WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);
我查看了MSDN文档,但没有看到任何提及.另外,这没有意义,因为如果您运行可执行文件,则必须先登录.
这只是ReSharper的搜索模式吗?
使用ILSpy,您可以查看GetCurrent
和GetCurrentInternal
的反编译版本,它们被GetCurrent
调用.结果是:
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
的风险./p>
ReSharper warns me about a possible NullReferenceException
in
WindowsIdentity windowsIdentity = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);
I looked in MSDN doc but didn't see any mention of this. Also, it doesn't make sense since if you run an executable, you have to be logged on.
Is this just a ReSharper search pattern?
Using ILSpy, you can look at a de-compiled version of GetCurrent
and GetCurrentInternal
, which GetCurrent
calls.The result is:
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));
}
Since threadOnly
is always false when calling from GetCurrent
, and the currentToken
must be valid for the other return statement, I don't think you're at risk of getting a null WindowsIdentity
.
这篇关于WindowsIdentity.GetCurrent()是否可以返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!