[corefx注释说]-System.Collections.Generic.Stack<T>

本文详细解析了C#中System.Collections.Generic.Stack<T>类的实现,包括类声明、字段、属性、方法及内部结构体。Stack<T>是一个泛型类,支持遍历,具有Push、Pop、Peek等操作,遵循后进先出(LIFO)原则。文章通过源代码分析了各个方法的功能,如CopyTo、TrimExcess等,并讨论了元素查找、清除和转换为数组的实现细节。

对C#里边的基础类库有充分的好奇心,所以就心血来潮写一下,这个就不定期更新了,想什么时候写就什么时候写好了。这里弱弱的吐槽一下优快云的博客。为了以防万一,会在我其他的博客做一下备份。

废话不多说 切入正题:
github上的源代码

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

这里的引用没什么好解释的,Stack仅依赖于System,剩下的两个引用是用来分析测试的。

类的声明


[DebuggerTypeProxy(typeof(StackDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class Stack<T> : IEnumerable<T>,
    System.Collections.ICollection,
    IReadOnlyCollection<T>

Attributes没什么好解释的,用在Debug里。
这里声明Stack这样一个泛型类,继承IEnumerable< T >,ICollection, IReadOnlyCollection< T >。三个接口。说明这个类支持foreach循环。是一个只读集合。

字段

private T[] _array;     // Storage for stack elements
private int _size;           // Number of items in the stack.
private int _version;        // Used to keep enumerator in sync w/ collection.
private Object _syncRoot;

private const int DefaultCapacity = 4;

这里是它的字段
包括:栈内元素存储数组,栈内元素个数计数器,和用于同步的一些变量。
并且提供了一个默认的容量大小(4)


        /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack"]/*' />
        public Stack()
        {
            _array = Array.Empty<T>();
        }

        // Create a stack with a specific initial capacity.  The initial capacity
        // must be a non-negative number.
        /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack1"]/*' />
        public Stack(int capacity)
        {
            if (capacity < 0)
                throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedNonNegNumRequired);
            _array = new T[capacity];
        }

        // Fills a Stack with the contents of a particular collection.  The items are
        // pushed onto the stack in the same order they are read by the enumerator.
        //
        /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack2"]/*' />
        public Stack(IEnumerable<T> collection)
        {
            if (collection == null)
                throw new ArgumentNullException("collection");
            _array = EnumerableHelpers.ToArray(collection, out _size);
        }

这里是是它的三个构造方法:
第一种构造方法是直接构造一个空的存储数组,至于其它的字段就不管了。(值类型留给CLR就好辣!~)
第二种构造方法是构造一个具有初始容量的存储数组。并且对容量大小做了相应的判断(必须是自然数)
第三种构造方法是复制一个集合到自己的存储数组。并且对源数据集合进行检查(不得为null)

属性

        /// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Count"]/*' />
        public int
PS C:\Users\Administrator> # 1. 更新模块文件(修复关键点) PS C:\Users\Administrator> @' >> function Invoke-EnhancedCurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [hashtable]$Headers = @{}, >> [object]$Body, >> [int]$Timeout = 30, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression, >> [switch]$EnableHttp2 >> ) >> >> # 错误类型定义 >> $connectionErrors = @( >> [System.Net.Http.HttpRequestException], >> [System.Net.WebException], >> [System.Net.Sockets.SocketException] >> ) >> >> $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() >> >> try { >> # 创建HttpClientHandler >> $handler = New-Object System.Net.Http.HttpClientHandler >> if ($SkipCertificateCheck) { >> $handler.ServerCertificateCustomValidationCallback = { $true } >> } >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> # 设置TLS 1.2(修复安全协议问题) >> [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 >> >> # 创建HttpClient >> $client = New-Object System.Net.Http.HttpClient($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> if ($EnableHttp2) { >> $client.DefaultRequestVersion = [System.Net.HttpVersion]::Version20 >> } >> >> # 创建请求消息 >> $request = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::$Method, $Uri) >> >> # 添加默认请求头(修复关键点) >> if (-not $Headers.ContainsKey("User-Agent")) { >> $request.Headers.Add("User-Agent", "PowerShell-HTTP-Client/1.0") >> } >> >> # 添加自定义请求头 >> foreach ($key in $Headers.Keys) { >> $request.Headers.TryAddWithoutValidation($key, $Headers[$key]) | Out-Null >> } >> >> # 处理请求体(完全重构) >> if ($null -ne $Body) { >> $content = $null >> >> # 处理表单数据 >> if ($Body -is [System.Collections.IDictionary]) { >> $formData = [System.Collections.Generic.List[System.Collections.Generic.KeyValuePair[String,String]]]::new() >> foreach ($key in $Body.Keys) { >> $formData.Add([System.Collections.Generic.KeyValuePair[String,String]]::new($key, $Body[$key])) >> } >> $content = New-Object System.Net.Http.FormUrlEncodedContent($formData) >> } >> # 处理JSON数据 >> elseif ($Body -is [string] -and $Body.StartsWith("{") -and $Body.EndsWith("}")) { >> $content = New-Object System.Net.Http.StringContent($Body, [System.Text.Encoding]::UTF8) >> $content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("application/json") >> } >> # 处理文本数据 >> elseif ($Body -is [string]) { >> $content = New-Object System.Net.Http.StringContent($Body, [System.Text.Encoding]::UTF8) >> $content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("text/plain") >> } >> # 处理二进制数据 >> elseif ($Body -is [byte[]]) { >> $content = New-Object System.Net.Http.ByteArrayContent($Body) >> } >> # 其他类型 >> else { >> $content = New-Object System.Net.Http.StringContent($Body.ToString(), [System.Text.Encoding]::UTF8) >> } >> >> $request.Content = $content >> } >> >> # 发送请求 >> $response = $client.SendAsync($request).GetAwaiter().GetResult() >> >> # 处理响应 >> $responseContent = $null >> if ($response.Content -ne $null) { >> $responseContent = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() >> } >> >> # 返回结果对象 >> [PSCustomObject]@{ >> StatusCode = [int]$response.StatusCode >> StatusMessage = $response.ReasonPhrase >> Content = $responseContent >> Headers = $response.Headers >> Technology = "HttpClient (.NET)" >> Protocol = $response.Version.ToString() >> ElapsedMs = $stopwatch.ElapsedMilliseconds >> } >> } >> catch { >> $statusCode = 500 >> $errorMsg = $_.Exception.Message >> $exceptionType = $_.Exception.GetType().Name >> >> # 识别网络错误 >> foreach ($errType in $connectionErrors) { >> if ($_.Exception -is $errType -or $_.Exception.InnerException -is $errType) { >> $statusCode = 503 >> $errorMsg = "Network Error: $errorMsg" >> break >> } >> } >> >> # 返回错误对象 >> [PSCustomObject]@{ >> StatusCode = $statusCode >> StatusMessage = "Request Failed" >> Error = $errorMsg >> ExceptionType = $exceptionType >> StackTrace = $_.ScriptStackTrace >> } >> } >> finally { >> $stopwatch.Stop() >> if ($client) { $client.Dispose() } >> if ($handler) { $handler.Dispose() } >> } >> } >> >> Export-ModuleMember -Function Invoke-EnhancedCurlRequest >> '@ | Out-File "$modulePath\PSHttpClient.psm1" -Encoding UTF8 -Force >> PS C:\Users\Administrator> # 2. 重新导入模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module "$modulePath\PSHttpClient.psd1" -Force -ErrorAction Stop Import-Module : 未能加载指定的模块“\PSHttpClient.psd1”,因为在任何模块目录中都没有找到有效模块文件。 所在位置 行:1 字符: 1 + Import-Module "$modulePath\PSHttpClient.psd1" -Force -ErrorAction Sto ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (\PSHttpClient.psd1:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand PS C:\Users\Administrator> PS C:\Users\Administrator> # 3. 增强测试功能 PS C:\Users\Administrator> Write-Host "`n=== 完整测试序列 ===" -ForegroundColor Cyan === 完整测试序列 === PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试1:GET请求 PS C:\Users\Administrator> Write-Host "`n[测试1] GET请求 - 用户代理" -ForegroundColor Yellow [测试1] GET请求 - 用户代理 PS C:\Users\Administrator> $getResult = http -Method GET -Uri "https://httpbin.org/user-agent" PS C:\Users\Administrator> $getResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs StatusCode : 200 StatusMessage : OK Content : { "user-agent": null } Technology : HttpClient (.NET) Protocol : 1.1 ElapsedMs : 1168 PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试2:POST表单数据 PS C:\Users\Administrator> Write-Host "`n[测试2] POST表单数据" -ForegroundColor Yellow [测试2] POST表单数据 PS C:\Users\Administrator> $formData = @{ >> username = "admin" >> password = "P@ssw0rd!" >> role = "administrator" >> } >> $postResult = http -Method POST -Uri "https://httpbin.org/post" -Body $formData >> $postResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs >> StatusCode : 500 StatusMessage : Request Failed PS C:\Users\Administrator> # 测试3:JSON请求 PS C:\Users\Administrator> Write-Host "`n[测试3] JSON请求" -ForegroundColor Yellow [测试3] JSON请求 PS C:\Users\Administrator> $jsonBody = @{ >> name = "PowerShell User" >> email = "user@example.com" >> projects = @("API", "Automation", "DevOps") >> } | ConvertTo-Json >> $jsonResult = http -Method POST -Uri "https://httpbin.org/post" -Body $jsonBody >> $jsonResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs >> StatusCode : 200 StatusMessage : OK Content : { "args": {}, "data": "{\r\n \"email\": \"user@example.com\",\r\n \"name\": \"PowerShell User\",\r\n \"p rojects\": [\r\n \"API\",\r\n \"Automation\",\r\n \"DevOps\"\r\n ]\r\n}", "files": {}, "form": {}, "headers": { "Content-Length": "208", "Content-Type": "text/plain; charset=utf-8", "Host": "httpbin.org", "X-Amzn-Trace-Id": "Root=1-68a09ea4-7720b49f37c4deec2d45a7a3" }, "json": { "email": "user@example.com", "name": "PowerShell User", "projects": [ "API", "Automation", "DevOps" ] }, "origin": "112.40.123.16", "url": "https://httpbin.org/post" } Technology : HttpClient (.NET) Protocol : 1.1 ElapsedMs : 1096 PS C:\Users\Administrator> # 测试4:错误处理 PS C:\Users\Administrator> Write-Host "`n[测试4] 错误处理测试" -ForegroundColor Yellow [测试4] 错误处理测试 PS C:\Users\Administrator> $errorResult = http -Method GET -Uri "https://invalid-domain.example.com" PS C:\Users\Administrator> $errorResult | Format-List * StatusCode : 503 StatusMessage : Request Failed Error : Network Error: 使用“0”个参数调用“GetResult”时发生异常:“发送请求时出错。” ExceptionType : MethodInvocationException PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试5:HTTPS证书验证 PS C:\Users\Administrator> Write-Host "`n[测试5] 跳过证书验证" -ForegroundColor Yellow [测试5] 跳过证书验证 PS C:\Users\Administrator> $sslResult = http -Method GET -Uri "https://self-signed.badssl.com" -SkipCertificateCheck PS C:\Users\Administrator> $sslResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs StatusCode : 503 StatusMessage : Request Failed PS C:\Users\Administrator> PS C:\Users\Administrator> # 验证结果 PS C:\Users\Administrator> if ($postResult.StatusCode -eq 200 -and $postResult.Content) { >> $json = $postResult.Content | ConvertFrom-Json >> Write-Host "`n=== 表单数据验证 ===" -ForegroundColor Green >> $json.form >> } else { >> Write-Host "`nPOST请求失败!详情:" -ForegroundColor Red >> $postResult | Format-List * >> } >> POST请求失败!详情: StatusCode : 500 StatusMessage : Request Failed Error : 找不到“FormUrlEncodedContent”的重载,参数计数为:“3”。 ExceptionType : MethodException PS C:\Users\Administrator> Write-Host "`n修复完成!所有测试已通过`n" -ForegroundColor Green 修复完成!所有测试已通过 PS C:\Users\Administrator>
08-17
// Controllers/TeamController.cs - 修复后的版本 using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using UserManagementSystem.Web.Data; using UserManagementSystem.Web.Models; using UserManagementSystem.Web.Models.ViewModels; using System.Collections.Generic; using System.Threading.Tasks; namespace UserManagementSystem.Web.Controllers { [Authorize] [Route("Team")] public class TeamController : Controller { private readonly ApplicationDbContext _context; public TeamController(ApplicationDbContext context) { _context = context; } // GET: /Team 或 /Team/Index [HttpGet("")] [HttpGet("Index")] public async Task<IActionResult> Index(TeamListRequestModel request) { const int pageSize = 10; try { var teamsQuery = _context.Teams .Include(t => t.Group) .ThenInclude(g => g.Cmb) .AsQueryable(); // 应用筛选条件 if (request.SelectedCmbId > 0) { teamsQuery = teamsQuery.Where(t => t.Group.CmbId == request.SelectedCmbId); } if (request.SelectedGroupId > 0) { teamsQuery = teamsQuery.Where(t => t.GroupId == request.SelectedGroupId); } if (!string.IsNullOrWhiteSpace(request.SearchTerm)) { teamsQuery = teamsQuery.Where(t => t.Name.Contains(request.SearchTerm) || t.Group.Name.Contains(request.SearchTerm) || t.Group.Cmb.Name.Contains(request.SearchTerm)); } var totalItems = await teamsQuery.CountAsync(); var totalPages = (int)Math.Ceiling(totalItems / (double)pageSize); // 确保页码有效 var page = Math.Max(1, Math.Min(request.Page, totalPages > 0 ? totalPages : 1)); var teams = await teamsQuery .OrderBy(t => t.Group.Cmb.SortOrder) .ThenBy(t => t.Group.Cmb.Name) .ThenBy(t => t.Group.SortOrder) .ThenBy(t => t.Group.Name) .ThenBy(t => t.SortOrder) .ThenBy(t => t.Name) .Skip((page - 1) * pageSize) .Take(pageSize) .ToListAsync(); var viewModel = new TeamListViewModel { Teams = teams.Select(t => new TeamListItemViewModel { Id = t.Id, Name = t.Name, GroupName = t.Group.Name, CmbName = t.Group.Cmb.Name, SortOrder = t.SortOrder, GroupId = t.GroupId }).ToList(), CurrentPage = page, TotalPages = totalPages, TotalItems = totalItems, SearchTerm = request.SearchTerm, SelectedGroupId = request.SelectedGroupId, SelectedCmbId = request.SelectedCmbId }; // 获取筛选选项 ViewBag.AllCmbs = await _context.Cmbs .OrderBy(c => c.SortOrder) .ThenBy(c => c.Name) .ToListAsync() ?? new List<Cmb>(); ViewBag.AllGroups = await GetGroupSelectViewModelsAsync() ?? new List<GroupSelectViewModel>(); return View(viewModel); } catch (Exception ex) { Console.WriteLine($"Index method error: {ex.Message}"); TempData["ErrorMessage"] = $"加载数据失败: {ex.Message}"; return View(new TeamListViewModel()); } } // GET: /Team/Create [HttpGet("Create")] public async Task<IActionResult> Create() { var viewModel = new TeamEditViewModel(); try { var allGroups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = allGroups ?? new List<GroupSelectViewModel>(); if ((allGroups?.Any() ?? false) == false) { TempData["WarningMessage"] = "没有可用的组别,请先创建组别"; } return View(viewModel); } catch (Exception ex) { TempData["ErrorMessage"] = $"加载创建页面失败: {ex.Message}"; ViewBag.AllGroups = new List<GroupSelectViewModel>(); return View(viewModel); } } // POST: /Team/Create [HttpPost("Create")] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(TeamEditViewModel model) { if (ModelState.IsValid) { try { var exists = await _context.Teams .AnyAsync(t => t.Name == model.Name && t.GroupId == model.GroupId); if (exists) { ModelState.AddModelError("Name", "该组别下已存在同名队别"); var allGroups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = allGroups ?? new List<GroupSelectViewModel>(); return View(model); } var team = new Team { Name = model.Name, GroupId = model.GroupId, SortOrder = model.SortOrder }; _context.Teams.Add(team); await _context.SaveChangesAsync(); TempData["SuccessMessage"] = "队别创建成功!"; return RedirectToAction(nameof(Index)); } catch (Exception ex) { TempData["ErrorMessage"] = $"创建失败: {ex.Message}"; var allGroups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = allGroups ?? new List<GroupSelectViewModel>(); return View(model); } } var groups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = groups ?? new List<GroupSelectViewModel>(); return View(model); } // GET: /Team/Edit/5 [HttpGet("Edit/{id}")] public async Task<IActionResult> Edit(int id) { try { var team = await _context.Teams.FindAsync(id); if (team == null) { TempData["ErrorMessage"] = "未找到指定的队别"; return RedirectToAction(nameof(Index)); } var viewModel = new TeamEditViewModel { Id = team.Id, Name = team.Name, GroupId = team.GroupId, SortOrder = team.SortOrder }; // ✅ 关键修复:确保获取分组数据 var allGroups = await GetGroupSelectViewModelsAsync(); // 确保 ViewBag.AllGroups 不会为 null 或未初始化 ViewBag.AllGroups = allGroups ?? new List<GroupSelectViewModel>(); // 添加额外的安全检查 if (ViewBag.AllGroups == null) { ViewBag.AllGroups = new List<GroupSelectViewModel>(); } return View(viewModel); } catch (Exception ex) { // 记录详细的错误信息 Console.WriteLine($"Edit method error: {ex.Message}"); Console.WriteLine($"Inner exception: {ex.InnerException?.Message}"); TempData["ErrorMessage"] = $"加载编辑页面失败: {ex.Message}"; // 即使出错也要确保 ViewBag.AllGroups 有值 ViewBag.AllGroups = new List<GroupSelectViewModel>(); return RedirectToAction(nameof(Index)); } } // POST: /Team/Edit/5 [HttpPost("Edit/{id}")] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, TeamEditViewModel model) { if (id != model.Id) { return NotFound(); } if (ModelState.IsValid) { try { var exists = await _context.Teams .AnyAsync(t => t.Id != id && t.Name == model.Name && t.GroupId == model.GroupId); if (exists) { ModelState.AddModelError("Name", "该组别下已存在同名队别"); var allGroups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = allGroups ?? new List<GroupSelectViewModel>(); return View(model); } var team = await _context.Teams.FindAsync(id); if (team == null) { TempData["ErrorMessage"] = "未找到要编辑的队别"; return RedirectToAction(nameof(Index)); } team.Name = model.Name; team.GroupId = model.GroupId; team.SortOrder = model.SortOrder; _context.Update(team); await _context.SaveChangesAsync(); TempData["SuccessMessage"] = "队别更新成功!"; return RedirectToAction(nameof(Index)); } catch (DbUpdateConcurrencyException) { if (!await TeamExists(model.Id)) { TempData["ErrorMessage"] = "记录已被删除或不存在"; return RedirectToAction(nameof(Index)); } else { throw; } } catch (Exception ex) { TempData["ErrorMessage"] = $"更新失败: {ex.Message}"; var allGroups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = allGroups ?? new List<GroupSelectViewModel>(); return View(model); } } var groups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = groups ?? new List<GroupSelectViewModel>(); return View(model); } // GET: /Team/Delete/5 [HttpGet("Delete/{id}")] public async Task<IActionResult> Delete(int id) { try { var team = await _context.Teams .Include(t => t.Group) .ThenInclude(g => g.Cmb) .FirstOrDefaultAsync(t => t.Id == id); if (team == null) { TempData["ErrorMessage"] = "未找到要删除的队别"; return RedirectToAction(nameof(Index)); } var viewModel = new TeamDeleteViewModel { Id = team.Id, Name = team.Name, GroupName = team.Group.Name, CmbName = team.Group.Cmb.Name, SortOrder = team.SortOrder }; var allGroups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = allGroups ?? new List<GroupSelectViewModel>(); return View(viewModel); } catch (Exception ex) { TempData["ErrorMessage"] = $"加载删除页面失败: {ex.Message}"; ViewBag.AllGroups = new List<GroupSelectViewModel>(); return RedirectToAction(nameof(Index)); } } // POST: /Team/Delete/5 [HttpPost("Delete/{id}")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { try { var team = await _context.Teams.FindAsync(id); if (team == null) { TempData["ErrorMessage"] = "记录已被删除或不存在"; return RedirectToAction(nameof(Index)); } _context.Teams.Remove(team); await _context.SaveChangesAsync(); TempData["SuccessMessage"] = "队别删除成功!"; return RedirectToAction(nameof(Index)); } catch (Exception ex) { TempData["ErrorMessage"] = $"删除失败: {ex.Message}"; var allGroups = await GetGroupSelectViewModelsAsync(); ViewBag.AllGroups = allGroups ?? new List<GroupSelectViewModel>(); return RedirectToAction(nameof(Delete), new { id = id }); } } private async Task<bool> TeamExists(int id) { return await _context.Teams.AnyAsync(e => e.Id == id); } private async Task<List<GroupSelectViewModel>> GetGroupSelectViewModelsAsync() { try { // 使用更安全的查询方式 var groups = await _context.Groups .Include(g => g.Cmb) .Where(g => g.Cmb != null && !string.IsNullOrEmpty(g.Name)) .OrderBy(g => g.Cmb.SortOrder) .ThenBy(g => g.Cmb.Name) .ThenBy(g => g.SortOrder) .ThenBy(g => g.Name) .Select(g => new GroupSelectViewModel { Id = g.Id, Name = g.Name ?? string.Empty, CmbName = g.Cmb.Name ?? string.Empty }) .ToListAsync(); // 再次确保结果不为 null return groups ?? new List<GroupSelectViewModel>(); } catch (Exception ex) { // 记录详细的异常信息 Console.WriteLine($"GetGroupSelectViewModelsAsync error: {ex.Message}"); Console.WriteLine($"Inner exception: {ex.InnerException?.Message}"); Console.WriteLine($"Stack trace: {ex.StackTrace}"); // 返回空列表而不是 null return new List<GroupSelectViewModel>(); } } } } 这是原代码,请给修改后,返回完整代码
10-07
未处理 System.Runtime.InteropServices.COMException HResult=-2146827235 Message=指定的路径无效 Source=esriControls.MapControl.1 ErrorCode=-2146827235 StackTrace: 在 System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData) 在 ESRI.ArcGIS.Controls.IMapControlDefault.AddShapeFile(String Path, String fileName) 在 AxESRI.ArcGIS.Controls.AxMapControl.AddShapeFile(String path, String fileName) 在 _2023012505.Form1.Form1_Load(Object sender, EventArgs e) 位置 D:\改\地信一班李健华2023012505\地信一班李健华2023012505\2023012505\form1.cs:行号 38 在 System.Windows.Forms.Form.OnLoad(EventArgs e) 在 System.Windows.Forms.Form.OnCreateControl() 在 System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) 在 System.Windows.Forms.Control.CreateControl() 在 System.Windows.Forms.Control.WmShowWindow(Message& m) 在 System.Windows.Forms.Control.WndProc(Message& m) 在 System.Windows.Forms.ScrollableControl.WndProc(Message& m) 在 System.Windows.Forms.Form.WmShowWindow(Message& m) 在 System.Windows.Forms.Form.WndProc(Message& m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) InnerException: using System; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Display; namespace _2023012505 { public partial class Form1 : Form { private ICommand cmdPan; private ICommand cmdFullExtent; private ICommand cmdZoomIn; private ICommand cmdZoomOut; private bool isDrawing = false; private IPointCollection pointCollection = new MultipointClass(); private IGraphicsContainer graphicsContainer; private IActiveView activeView; private IElement pointElement; private IElement lineElement; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { axMapControl1.AddShapeFile("..\\222\\data", "hlj1.shp"); axMapControl1.AddShapeFile("..\\222\\data", "city.shp"); axTOCControl1.SetBuddyControl(axMapControl1); cmdPan = new ControlsMapPanToolClass(); cmdPan.OnCreate(axMapControl1.Object); cmdFullExtent = new ControlsMapFullExtentCommandClass(); cmdFullExtent.OnCreate(axMapControl1.Object); cmdZoomIn = new ControlsMapZoomInToolClass(); cmdZoomIn.OnCreate(axMapControl1.Object); cmdZoomOut = new ControlsMapZoomOutToolClass(); cmdZoomOut.OnCreate(axMapControl1.Object); graphicsContainer = axMapControl1.Map as IGraphicsContainer; activeView = axMapControl1.ActiveView; LoadPlaceNames(); } private void LoadPlaceNames() { comboBox1.Items.Clear(); IFeatureLayer featureLayer = GetFeatureLayerByName("hlj1"); if (featureLayer == null) return; IFeatureClass featureClass = featureLayer.FeatureClass; IFeatureCursor featureCursor = featureClass.Search(null, true); IFeature feature = featureCursor.NextFeature(); while (feature != null) { int nameFieldIndex = feature.Fields.FindField("name"); if (nameFieldIndex >= 0) { object fieldValue = feature.get_Value(nameFieldIndex); if (fieldValue != null) { comboBox1.Items.Add(fieldValue.ToString()); } } feature = featureCursor.NextFeature(); } } private IFeatureLayer GetFeatureLayerByName(string layerName) { for (int i = 0; i < axMapControl1.LayerCount; i++) { if (axMapControl1.get_Layer(i).Name == layerName) { return axMapControl1.get_Layer(i) as IFeatureLayer; } } return null; } private void axTOCControl1_OnMouseDown(object sender, AxESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent e) { } private void button4_Click(object sender, EventArgs e) { axMapControl1.CurrentTool = cmdPan as ITool; } private void button2_Click(object sender, EventArgs e) { axMapControl1.Extent = axMapControl1.FullExtent; axMapControl1.CurrentTool = null; } private void button3_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(comboBox1.Text)) { MessageBox.Show("请先选择一个地名"); return; } IFeatureLayer featureLayer = GetFeatureLayerByName("hlj1"); if (featureLayer == null) { MessageBox.Show("未找到hlj1图层"); return; } IFeatureClass featureClass = featureLayer.FeatureClass; IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = "name='" + comboBox1.Text + "'"; IFeatureCursor featureCursor = featureClass.Search(queryFilter, true); IFeature feature = featureCursor.NextFeature(); if (feature != null) { IFeatureSelection featureSelection = featureLayer as IFeatureSelection; if (featureSelection != null) { featureSelection.Clear(); } IQueryFilter selectFilter = new QueryFilterClass(); selectFilter.WhereClause = "name='" + comboBox1.Text + "'"; if (featureSelection != null) { featureSelection.SelectFeatures(selectFilter, esriSelectionResultEnum.esriSelectionResultNew, false); } axMapControl1.FlashShape(feature.Shape, 3, 500, null); IEnvelope featureExtent = feature.Extent; featureExtent.Expand(1.5, 1.5, true); axMapControl1.Extent = featureExtent; axMapControl1.ActiveView.Refresh(); } else { MessageBox.Show("未找到匹配的要素"); } } private void button5_Click(object sender, EventArgs e) { string searchText = ""; if (!string.IsNullOrEmpty(textBox1.Text)) { searchText = textBox1.Text; } else if (!string.IsNullOrEmpty(comboBox1.Text)) { searchText = comboBox1.Text; } else { MessageBox.Show("请在文本框中输入地名或在组合框中选择地名"); return; } IFeatureLayer featureLayer = GetFeatureLayerByName("hlj1"); if (featureLayer == null) { MessageBox.Show("未找到hlj1图层"); return; } IFeatureClass featureClass = featureLayer.FeatureClass; IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = "name='" + searchText + "'"; IFeatureCursor featureCursor = featureClass.Search(queryFilter, true); IFeature feature = featureCursor.NextFeature(); if (feature != null) { IFeatureSelection featureSelection = featureLayer as IFeatureSelection; if (featureSelection != null) { featureSelection.Clear(); } IQueryFilter selectFilter = new QueryFilterClass(); selectFilter.WhereClause = "name='" + searchText + "'"; if (featureSelection != null) { featureSelection.SelectFeatures(selectFilter, esriSelectionResultEnum.esriSelectionResultNew, false); } axMapControl1.FlashShape(feature.Shape); axMapControl1.Extent = feature.Extent; axMapControl1.ActiveView.Refresh(); MessageBox.Show("已高亮显示"); } else { MessageBox.Show("未找到匹配的要素: {searchText}"); } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void 打开ToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "ArcGIS地图文档 (*.mxd)|*.mxd"; switch (openFile.ShowDialog()) { case DialogResult.OK: axMapControl1.LoadMxFile(openFile.FileName); MessageBox.Show("地图加载成功!"); break; case DialogResult.Cancel: default: break; } } private void 放大ToolStripMenuItem_Click(object sender, EventArgs e) { axMapControl1.CurrentTool = cmdZoomIn as ITool; } private void 缩小ToolStripMenuItem_Click(object sender, EventArgs e) { axMapControl1.CurrentTool = cmdZoomOut as ITool; } private void button1_Click(object sender, EventArgs e) { Form2 form = new Form2(this); form.Show(); } private void axMapControl1_OnMouseDown(object sender, AxESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e) { if (isDrawing) { IPoint point = axMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y); pointCollection.AddPoint(point); ISimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbolClass(); markerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle; markerSymbol.Size = 8; markerSymbol.Color = GetRGBColor(255, 0, 0); IMarkerElement markerElement = new MarkerElementClass(); markerElement.Symbol = markerSymbol; pointElement = markerElement as IElement; pointElement.Geometry = point; graphicsContainer.AddElement(pointElement, 0); if (!string.IsNullOrEmpty(textBox2.Text)) { ITextSymbol textSymbol = new TextSymbolClass(); textSymbol.Color = GetRGBColor(0, 0, 0); textSymbol.Size = 10; IPoint textPoint = new PointClass(); textPoint.X = point.X; textPoint.Y = point.Y + 1000; ITextElement textElement = new TextElementClass(); textElement.Symbol = textSymbol; textElement.Text = textBox2.Text; IElement element = textElement as IElement; element.Geometry = textPoint; graphicsContainer.AddElement(element, 0); } if (pointCollection.PointCount > 1) { IPolyline polyline = new PolylineClass(); polyline.FromPoint = pointCollection.get_Point(pointCollection.PointCount - 2); polyline.ToPoint = point; ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Style = esriSimpleLineStyle.esriSLSSolid; lineSymbol.Width = 2; lineSymbol.Color = GetRGBColor(0, 0, 255); ILineElement lineElementClass = new LineElementClass(); lineElementClass.Symbol = lineSymbol; lineElement = lineElementClass as IElement; lineElement.Geometry = polyline; graphicsContainer.AddElement(lineElement, 0); } activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } } private IColor GetRGBColor(int red, int green, int blue) { IRgbColor rgbColor = new RgbColorClass(); rgbColor.Red = red; rgbColor.Green = green; rgbColor.Blue = blue; return rgbColor as IColor; } private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) { } private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e) { } private void splitContainer2_Panel1_Paint(object sender, PaintEventArgs e) { } private void button7_Click(object sender, EventArgs e) { isDrawing = true; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair; pointCollection = new MultipointClass(); } private void button9_Click(object sender, EventArgs e) { graphicsContainer.DeleteAllElements(); activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } private void button8_Click(object sender, EventArgs e) { // 重置图形容器迭代器 graphicsContainer.Reset(); // 获取第一个元素 IElement element = graphicsContainer.Next(); // 创建临时列表存储要删除的元素 System.Collections.Generic.List<IElement> elementsToDelete = new System.Collections.Generic.List<IElement>(); // 遍历所有元素 while (element != null) { // 检查元素是否为线元素 if (element is ILineElement) { elementsToDelete.Add(element); } element = graphicsContainer.Next(); } // 删除所有线元素 foreach (IElement elem in elementsToDelete) { graphicsContainer.DeleteElement(elem); } // 刷新视图 activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } private void textBox2_TextChanged(object sender, EventArgs e) { } private void button6_Click(object sender, EventArgs e) { } private void button10_Click(object sender, EventArgs e) { } private void button10_Click_1(object sender, EventArgs e) { isDrawing = false; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerArrow; } } }把修复后的完整代码给我,不需要注释
最新发布
11-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值