哪些.NET Framework类实现了IDisposable?

8

似乎这个问题需要有文档记录,但我找不到任何相关的信息。也许是我的谷歌搜索能力正在减弱。


我认为你试图反其道而行。实现IDisposable接口的类非常多,仅得到它们的列表没有“非微不足道”的目的。如果你想知道一个特定的类是否实现了IDisposable接口,有多种方法可以做到,从帮助和MSDN库到在立即窗口中输入命令?theClass is IDisposable(在运行时...)。你是想找一个可以贴在墙上的清单吗? - Cos Callis
1
@goombaloon,选择编码路线吧,它比MSDN更短,更重要的是:更可靠。更不用说在MSDN上存在这样一个链接也没有任何实际意义。 - Darin Dimitrov
1
我正在撰写一篇文章,希望能够引用实现IDisposable接口的.NET Framework类列表。 因此,在某种程度上,是的,我有点在寻找“可以钉在墙上的清单”。 - goombaloon
@goombaloon,你所说的*.NET Framework class*是什么意思?在你澄清这个概念之前,我怀疑你会找到一个简单的答案。 - Darin Dimitrov
@Darin - 是的,我应该澄清一下。我对System.*命名空间感兴趣。 - goombaloon
显示剩余3条评论
3个回答

12

您需要知道这取决于您所谓的.NET Framework类。您可能需要指定您正在寻找哪些程序集。有了这些信息,您可以加载这些程序集并使用反射列出在给定程序集中实现IDisposable的所有公共类型。让我们以System程序集为例:

class Program
{
    static void Main()
    {
        var types = Assembly
            .Load("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            .GetTypes()
            .Where(t => typeof(IDisposable).IsAssignableFrom(t))
            .OrderBy(t => t.Name);
        foreach (var type in types)
        {
            Console.WriteLine(type);
        }
    }
}

这段代码对.NET Core程序集不起作用吗?我正在运行.NET Core,但看不到任何返回的类型。 - Kritul Rathod
以下是我在 .Net Core 中使用的代码:var types = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.StartsWith("System")) .SelectMany(x => x.GetTypes()) .Where(t => typeof(IDisposable).IsAssignableFrom(t)) .Select(t => new { Name = t.Name, Namespace = t.Namespace, Assembly = t.GetTypeInfo().Assembly }); foreach (var type in types) { Console.WriteLine(type); } - Kritul Rathod

6

使用Darin Dimitrov提出的代码,这是一个简单的C#控制台应用程序中实现IDisposable接口的框架类列表:

Microsoft.CSharp.CSharpCodeProvider Microsoft.VisualBasic.VBCodeProvider Microsoft.Win32.SafeHandles.SafeEventLogReadHandle Microsoft.Win32.SafeHandles.SafeEventLogWriteHandle Microsoft.Win32.SafeHandles.SafeFileMappingHandle Microsoft.Win32.SafeHandles.SafeFileMapViewHandle Microsoft.Win32.SafeHandles.SafeLibraryHandle Microsoft.Win32.SafeHandles.SafeLocalMemHandle Microsoft.Win32.SafeHandles.SafeProcessHandle Microsoft.Win32.SafeHandles.SafeThreadHandle Microsoft.Win32.SafeHandles.SafeTimerHandle Microsoft.Win32.SafeHandles.SafeUserTokenHandle Microsoft.Win32.WinInetCache+ReadStream Microsoft.Win32.WinInetCache+WriteStream System.CodeDom.Compiler.CodeDomProvider System.CodeDom.Compiler.IndentedTextWriter System.CodeDom.Compiler.TempFileCollection System.Collections.Concurrent.BlockingCollection1 System.Collections.Generic.LinkedList1+Enumerator System.Collections.Generic.Queue1+Enumerator System.Collections.Generic.SortedDictionary2+Enumerator System.Collections.Generic.SortedDictionary2+KeyCollection+Enumerator System.Collections.Generic.SortedDictionary2+ValueCollection+Enumerator System.Collections.Generic.SortedList2+Enumerator System.Collections.Generic.SortedList2+SortedListKeyEnumerator System.Collections.Generic.SortedList2+SortedListValueEnumerator System.Collections.Generic.SortedSet1+d__12 System.Collections.Generic.SortedSet1+Enumerator System.Collections.Generic.Stack1+Enumerator System.Collections.ObjectModel.ObservableCollection1+SimpleMonitor System.ComponentModel.BackgroundWorker System.ComponentModel.Component System.ComponentModel.Container System.ComponentModel.Design.DesignerTransaction System.ComponentModel.Design.IDesigner System.ComponentModel.Design.IRootDesigner System.ComponentModel.Design.ITreeDesigner System.ComponentModel.Design.Serialization.SerializationStore System.ComponentModel.Design.ServiceContainer System.ComponentModel.EventHandlerList System.ComponentModel.IContainer System.ComponentModel.INestedContainer System.ComponentModel.License System.ComponentModel.LicFileLicenseProvider+LicFileLicense System.ComponentModel.MarshalByValueComponent System.ComponentModel.NestedContainer System.Configuration.ClientSettingsStore+QuotaEnforcedStream System.Diagnostics.AsyncStreamReader System.Diagnostics.ConsoleTraceListener System.Diagnostics.DefaultTraceListener System.Diagnostics.DelimitedListTraceListener System.Diagnostics.EventLog System.Diagnostics.EventLogEntry System.Diagnostics.EventLogInternal System.Diagnostics.EventLogTraceListener System.Diagnostics.PerformanceCounter System.Diagnostics.Process System.Diagnostics.ProcessModule System.Diagnostics.ProcessThread System.Diagnostics.ProcessWaitHandle System.Diagnostics.TextWriterTraceListener System.Diagnostics.TraceListener System.Diagnostics.XmlWriterTraceListener System.IO.Compression.DeflateStream System.IO.Compression.GZipStream System.IO.FileSystemWatcher System.IO.Ports.SerialPort System.IO.Ports.SerialStream System.Media.SoundPlayer System.Net.AsyncRequestContext System.Net.Base64Stream System.Net.BaseWebProxyFinder System.Net.BufferedReadStream System.Net.Cache.BaseWrapperStream System.Net.Cache.CombinedReadStream System.Net.Cache.ForwardingReadStream System.Net.Cache.MetadataUpdateStream System.Net.Cache.RangeStream System.Net.Cache.SingleItemRequestCache+ReadOnlyStream System.Net.Cache.SingleItemRequestCache+WriteOnlyStream System.Net.ClosableStream System.Net.CommandStream System.Net.Connection System.Net.ConnectStream System.Net.DeflateWrapperStream System.Net.DelegatedStream System.Net.DirectProxy System.Net.FileWebResponse System.Net.FileWebStream System.Net.FtpControlStream System.Net.FtpDataStream System.Net.FtpWebResponse System.Net.FtpWebResponse+EmptyStream System.Net.GZipWrapperStream System.Net.HttpListener System.Net.HttpListenerResponse System.Net.HttpRequestQueueV2Handle System.Net.HttpRequestStream System.Net.HttpResponseStream System.Net.HttpServerSessionHandle System.Net.HttpWebResponse System.Net.HybridWebProxyFinder System.Net.IWebProxyFinder System.Net.ListenerPrefixEnumerator System.Net.Mail.AlternateView System.Net.Mail.AlternateViewCollection System.Net.Mail.Attachment System.Net.Mail.AttachmentBase System.Net.Mail.AttachmentCollection System.Net.Mail.LinkedResource System.Net.Mail.LinkedResourceCollection System.Net.Mail.MailMessage System.Net.Mail.SmtpClient System.Net.Mail.SmtpPooledStream System.Net.Mime.MimePart System.Net.Mime.QEncodedStream System.Net.Mime.QuotedPrintableStream System.Net.Mime.SevenBitStream System.Net.NetWebProxyFinder System.Net.NetworkAddressChangePolled System.Net.NetworkInformation.Ping System.Net.NetworkInformation.SafeCancelMibChangeNotify System.Net.NetworkInformation.SafeFreeMibTable System.Net.PooledStream System.Net.ProxyChain System.Net.ProxyChain+ProxyEnumerator System.Net.ProxyScriptChain System.Net.RequestContextBase System.Net.SafeCloseHandle System.Net.SafeCloseIcmpHandle System.Net.SafeCloseSocket System.Net.SafeCloseSocket+InnerSafeCloseSocket System.Net.SafeCloseSocketAndEvent System.Net.SafeCredentialReference System.Net.Safe

以下是 System.Windows.Forms 的列表:

System.Deployment.Internal.Isolation.BLOB System.Deployment.Internal.Isolation.Manifest.AssemblyReferenceDependentAssemblyEntry System.Deployment.Internal.Isolation.Manifest.DirectoryEntry System.Deployment.Internal.Isolation.Manifest.FileEntry System.Deployment.Internal.Isolation.Manifest.HashElementEntry System.Deployment.Internal.Isolation.Manifest.MetadataSectionEntry System.Deployment.Internal.Isolation.Manifest.MuiResourceMapEntry System.Deployment.Internal.Isolation.Manifest.MuiResourceTypeIdIntEntry System.Deployment.Internal.Isolation.Manifest.MuiResourceTypeIdStringEntry System.Deployment.Internal.Isolation.Manifest.RegistryKeyEntry System.Deployment.Internal.Isolation.Store+ApplicationPathLock System.Deployment.Internal.Isolation.Store+AssemblyPathLock System.Deployment.Internal.Isolation.Store+IPathLock System.Deployment.Internal.Isolation.StoreTransaction System.Resources.ResXResourceReader System.Resources.ResXResourceSet System.Resources.ResXResourceWriter System.Security.Policy.TrustManagerMoreInformation System.Security.Policy.TrustManagerPromptUI System.Windows.Forms.Application+MarshalingControl System.Windows.Forms.Application+ModalApplicationContext System.Windows.Forms.Application+ParkingWindow System.Windows.Forms.ApplicationContext System.Windows.Forms.ArrangedElement System.Windows.Forms.AxHost System.Windows.Forms.AxHost+OleInterfaces System.Windows.Forms.BindingNavigator System.Windows.Forms.BindingSource System.Windows.Forms.Button System.Windows.Forms.ButtonBase System.Windows.Forms.CachedItemHdcInfo System.Windows.Forms.CheckBox System.Windows.Forms.CheckedListBox System.Windows.Forms.ColorDialog System.Windows.Forms.ColumnHeader System.Windows.Forms.ComboBox System.Windows.Forms.CommonDialog System.Windows.Forms.ContainerControl System.Windows.Forms.ContextMenu System.Windows.Forms.ContextMenuStrip System.Windows.Forms.Control System.Windows.Forms.Control+ActiveXImpl+AdviseHelper+ComConnectionPoint System.Windows.Forms.Control+ActiveXImpl+AdviseHelper+ComConnectionPointContainer System.Windows.Forms.Control+ActiveXImpl+AdviseHelper+SafeIUnknown System.Windows.Forms.Control+FontHandleWrapper System.Windows.Forms.Control+MetafileDCWrapper System.Windows.Forms.Control+MultithreadSafeCallScope System.Windows.Forms.Control+PrintPaintEventArgs System.Windows.Forms.Cursor System.Windows.Forms.DataGrid System.Windows.Forms.DataGridBoolColumn System.Windows.Forms.DataGridColumnStyle System.Windows.Forms.DataGridTableStyle System.Windows.Forms.DataGridTextBox System.Windows.Forms.DataGridTextBoxColumn System.Windows.Forms.DataGridView System.Windows.Forms.DataGridViewBand System.Windows.Forms.DataGridViewButtonCell System.Windows.Forms.DataGridViewButtonColumn System.Windows.Forms.DataGridViewCell System.Windows.Forms.DataGridViewCheckBoxCell System.Windows.Forms.DataGridViewCheckBoxColumn System.Windows.Forms.DataGridViewColumn System.Windows.Forms.DataGridViewColumnHeaderCell System.Windows.Forms.DataGridViewComboBoxCell System.Windows.Forms.DataGridViewComboBoxColumn System.Windows.Forms.DataGridViewComboBoxEditingControl System.Windows.Forms.DataGridViewHeaderCell System.Windows.Forms.DataGridViewImageCell System.Windows.Forms.DataGridViewImageColumn System.Windows.Forms.DataGridViewLinkCell System.Windows.Forms.DataGridViewLinkColumn System.Windows.Forms.DataGridViewRow System.Windows.Forms.DataGridViewRowHeaderCell System.Windows.Forms.DataGridViewTextBoxCell System.Windows.Forms.DataGridViewTextBoxColumn System.Windows.Forms.DataGridViewTextBoxEditingControl System.Windows.Forms.DataGridViewTopLeftHeaderCell System.Windows.Forms.DataStreamFromComStream System.Windows.Forms.DateTimePicker System.Windows.Forms.Design.ComponentEditorForm System.Windows.Forms.Design.ComponentEditorForm+PageSelector System.Windows.Forms.Design.ComponentEditorPage System.Windows.Forms.DomainUpDown System.Windows.Forms.ErrorProvider System.Windows.Forms.FileDialog System.Windows.Forms.FlowLayoutPanel System.Windows.Forms.FolderBrowserDialog System.Windows.Forms.FontDialog System.Windows.Forms.Form System.Windows.Forms.Form+SecurityToolTip System.Windows.Forms.GroupBox System.Windows.Forms.HelpProvider System.Windows.Forms.HScrollBar System.Windows.Forms.HtmlDocument+HtmlDocumentShim System.Windows.Forms.HtmlElement+HtmlElementShim System.Windows.Forms.HtmlHistory System.Windows.Forms.HtmlShim System.Windows.Forms.HtmlShimManager System.Windows.Forms.HtmlWindow+HtmlWindowShim System.Windows.Forms.IBindableComponent System.Windows.Forms.ImageList System.Windows.Forms.ImageList+NativeImageList System.Windows.Forms.ImageListStreamer System.Windows.Forms.Internal.DeviceContext System.Windows.Forms.Internal.WindowsBrush System.Windows.Forms.Internal.WindowsFont System.Windows.Forms.Internal.WindowsGraphics System.Windows.Forms.Internal.WindowsPen System.Windows.Forms.Internal.WindowsRegion System.Windows.Forms.Internal.WindowsSolidBrush System.Windows.Forms.Label System.Windows.Forms.Layout.IArrangedElement System.Windows.Forms.Layout.LayoutTransaction System.Windows.Forms.Layout.NullLayoutTransaction System.Windows.Forms.LinkLabel System.Windows.Forms.ListBox System.Windows.Forms.ListControl System.Windows.Forms.ListView System.Windows.Forms.MainMenu System.Windows.Forms.MaskedTextBox System.Windows.Forms.MdiClient System.Windows.Forms.MdiControlStrip System.Windows.Forms.MdiControlStrip+ControlBoxMenuItem System.Windows.Forms.MdiControlStrip+SystemMenuItem System.Windows.Forms.MdiWindowDialog System.Windows.Forms

1
为什么要获取实现 IDisposable 接口的所有类的列表?更相关的问题似乎是“如何判断一个类是否实现了 IDisposable 接口?” 如果您需要文档,MSDN 将告诉您给定类实现了哪些接口。如果您需要在编译时知道,编译器将在您尝试将不是实现 IDisposable 接口的类的实例包装在 using 块中时发出警告。如果您需要在运行时知道,您可以使用 var disposable = obj as IDisposable 并检查 disposable 是否为 null

如果您有一个特定的程序集想要了解,您可以使用反射遍历其类型并测试这些类型是否实现了 IDisposable 接口(使用

typeof(IDisposable).IsAssignableFrom(type)

其中的type是一個您從某個Assembly中加載出來的Type實例。


2
有时您希望获取实现IDisposable接口的类列表!例如,我正在审查代码并阅读我使用过的类列表时,我想起需要释放但我忘记调用Dispose()方法的类。当然,您可以检查每个类,但我发现Dimitrov的代码段和列表非常实用... - Knasterbax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接