调用者的许可与声明者的许可

Caller's Permission Vs Declarer's Permission

我在 MSDN 上阅读有关委托的内容,看到一行内容是

"注: 在调用者的安全权限下委派 运行,而不是声明者的权限

这是什么意思?

假设问题是关于 Windows 权限,而不是 .Net 代码访问安全性 (CAS)。

无论您在创建委托(即 box admin)时 运行 使用什么帐户代码,Windows 权限都将在实际调用时计算 - 这可能与在创建时间。

假设您 运行 执行模拟帐户(Windows 用户)的代码来访问某些文件:

// run under "account1" - has access to c:\myFile.txt
// current Environment.UserName = "account2"
Func<string,string> readAllFile = fileName => File.ReadAllText(fileName);

// start impersonation of account2 - has access to c:\otherFile.txt, 
// but not c:\myFile.txt
ImpersonateAccount("account2", readAllFile);
....

...ImpersonateAccout(string name, Func<string,string> readAllFile)
{
  // .... impersonation code omitted
  // current Environment.UserName = "account2"
  var text1 = readAllFile(@"c:\otherFile.txt"); // success
  var text2 = readAllFile(@"c:\myFile.txt"); // failure
  ....

在上面的示例 readAllFile 中,代码是 运行ning 在 account1 下创建的,但它没有该帐户的 "capture" 权限,因此以后不能委托读取 c:\myFile.txt "account2" 没有权限。

请注意,像局部变量一样委托 "capture" C# 级上下文,这可能会带来其他类型的上下文也被捕获的假设。 Window 安全上下文以及 .Net 执行上下文(例如当前线程的区域性)不是这种情况。