标签: using-statement

隐藏C#'使用参数的实现

我正在尝试从与本机代码共享的数据的结构(实际上是类,因此它的引用类型)中抽象编组IntPtr.

我有这个助手类:

class NativeStruct<StructType> : IDisposable
{
    public NativeStruct()
    {
        _DataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(StructType)));
        Marshal.PtrToStructure(_DataPtr, _Data);
    }
    public NativeStruct(IntPtr dataPtr)
    {
        _DataPtr = dataPtr;
        Marshal.PtrToStructure(_DataPtr, _Data);
    }

    void IDisposable.Dispose()
    {
        Marshal.StructureToPtr(_Data, _DataPtr, true);
    }

    public StructType Data { get { return _Data; } }

    IntPtr _DataPtr;
    public StructType _Data;
}
Run Code Online (Sandbox Code Playgroud)

无论如何都有隐含的代码:

using (Shared_s data = new Toolbox.NativeStruct<DataStruct>(myIntPtr).Data)
{
    data.someMember = someValue;
}
Run Code Online (Sandbox Code Playgroud)

一些方法来改变它

EditStruct(DataStruct, myIntPtr)
{
    data.someMember = someValue;
}
Run Code Online (Sandbox Code Playgroud)

在C++中,我会使用像

#define EditStruct(StructType, IntPtr) using  \
(Shared_s data = new Toolbox.NativeStruct<StructType>(IntPtr).data)
Run Code Online (Sandbox Code Playgroud)

c# using-statement

3
推荐指数
1
解决办法
155
查看次数

我应该使用using语句来创建Windows.Forms.Form对象吗?

我已阅读(在usingStatement(C#参考)上)该using语句应该用于释放使用非托管资源的托管类型(如文件和字体)使用的资源.所以开始将它与MySql类和相关的东西一起使用,但是如果你看一下Windows.Forms.Form类的一个对象,你会看到一个Dispose方法,这意味着这个类实现了IDisposable所以,我应该使用一个using语句来实现一个Windows.Forms.Form对象,如下面的情况?

private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
    using (AboutBoxProjeto about = new AboutBoxProjeto())
    {
        about.ShowDialog();
    }
}
Run Code Online (Sandbox Code Playgroud)

c# using-statement winforms

3
推荐指数
1
解决办法
1804
查看次数

正确的方法从另一个使用statment包含的类中撤回数据

我得到一个例外"无法访问已处置的对象.".我知道我得到了这个例外,因为在它有机会返回结果之前,该对象已被删除.我想知道的是什么是撤回物体的正确方法.我可能在我的代码中有不必要的步骤,可能这样做错了吗?

所以我在我的主课堂上有一个按钮点击事件.它调用下面代码中显示的方法.GetADComputer方法位于另一个名为ActiveDirectory.cs的类(我创建了一个类文件.cs)中.我在尝试访问被驱散对象的结果时发现了异常.

public static PrincipalSearchResult<Principal> GetADComputer(string pcName)
    {
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
        {
            using (ComputerPrincipal computer = new ComputerPrincipal(ctx))
            {
                computer.Name = String.Format("*{0}*", pcName);

                using (PrincipalSearcher searcher = new PrincipalSearcher())
                {
                    searcher.QueryFilter = computer;
                    return searcher.FindAll();
                }
            }
        }            
    }    
Run Code Online (Sandbox Code Playgroud)

c# using-statement winforms

3
推荐指数
1
解决办法
621
查看次数

“使用”语句中的 C# 匿名对象可靠吗?

想象一下这个片段:

using System;



public class Report {
    static int Level=0;

    public static void WriteLine(string Message) {
        Console.WriteLine("{0}{1}",new String(' ',4*Level),Message);
    }

    public class Indent:IDisposable {
        public Indent()            { Report.WriteLine("{"); ++Level; }
        void IDisposable.Dispose() { --Level; Report.WriteLine("}"); }
    }
}



class Program {
    static void Main() {
        Report.WriteLine("Started");
        Report.WriteLine("Calling submethod");
        using(new Report.Indent()) {
            Report.WriteLine("Submethod started");
            using(new Report.Indent()) Report.WriteLine("Subsub, maybe?");
            Report.WriteLine("Submethod reporting everything is fine");
            Report.WriteLine("Submethod finished");
        }
        Report.WriteLine("Finished");
    }
}
Run Code Online (Sandbox Code Playgroud)

产生结果:

Started
Calling submethod
{
    Submethod started
    {
        Subsub, maybe?
    }
    Submethod …
Run Code Online (Sandbox Code Playgroud)

c# dispose idisposable using using-statement

3
推荐指数
1
解决办法
918
查看次数

如何将一些使用语句设置为不冗余,即使它们是多余的?

通常,文件创建时会使用一组常用的using语句.有时甚至在充实课程后我也不需要一些自动生成的使用语句.但是,如果最终需要删除它们会导致问题,例如因使用System.Linq删除而导致的问题; 有没有办法告诉Visual Studio/Resharper不要抱怨某些使用语句是多余的?

例:

using System;
using System.Collections.Generic; // Don't need but want anyway without an error
using System.Linq; // Don't need but want anyway without an error
using System.Net;
using System.Text; // Don't need but want anyway without an error
using Acceptance.EndToEnd.Helpers;
using Acceptance.EndToEnd.Locators;
Run Code Online (Sandbox Code Playgroud)

c# resharper settings using-statement visual-studio-2015

3
推荐指数
1
解决办法
161
查看次数

using 语句中的“访问已处理的关闭”警告

我正在使用“使用语句”来确保正确清理 StreamWriter。

using (StreamWriter fout = new StreamWriter(tempFile))
{
    data.ForEach(line => fout?.WriteLine(line));
}
Run Code Online (Sandbox Code Playgroud)

我收到 ReSharper 警告“访问已处理的关闭”,据我所知,这是因为变量fout可能已关闭。我知道在某些用途中可能会发生,但在这种情况下,是否有可能fout在调用时已经被处理WriteLine

c# resharper idisposable using-statement

3
推荐指数
1
解决办法
1750
查看次数

使用 Visual Studio 2019 自动导入不起作用

我在使用 VS 2019 和 IntelliSense 时遇到以下选择性问题。

当我开始键入命名空间尚未导入的类名时,IntelliSense 会在“自动完成”列中建议它。一旦我按下tab而不是完成名称并导入 using 指令,它就会自动完成整个路径,例如:

输入 ' UserView...' ->App.Web.Areas.Users.ViewModels.UserViewModel

而不是导入 ->using App.Web.Areas.Users.ViewModels;并完成输入UserViewModel

但是,如果我写下整个类名,然后按Ctrl + .,则 IntelliSense 会导入 using 指令。

有人知道哪个设置会触发此行为吗?

c# intellisense using-statement visual-studio visual-studio-2019

3
推荐指数
1
解决办法
7988
查看次数

当有多个using语句时,它们会按顺序执行吗?

例如

  using (Stream ftpStream = ftpResponse.GetResponseStream())       // a             
  using (FileStream localFileStream = (new FileInfo(localFilePath)).Create()) // b
  {
                 ........do something
  }
Run Code Online (Sandbox Code Playgroud)

两个陈述a和b会按照我的顺序执行吗?并按顺序排列?

谢谢

c# dispose using using-statement

2
推荐指数
1
解决办法
149
查看次数

在streamwriter,streamreader之前使用声明的好处/使用

可能重复:
什么是C#使用块,为什么要使用它?

所以我刚刚注意到在msdn示例和一些stackoverflow问题上有回答,其中using语句在streamwriter等之前使用,但实际上有什么好处呢?因为我从未被教过/告知/读过任何使用它的理由.

            using (StreamReader sr = new StreamReader(path)) 
            {
                while (sr.Peek() >= 0) 
                    Console.WriteLine(sr.ReadLine());
            }
Run Code Online (Sandbox Code Playgroud)

代替:

            StreamReader sr = new StreamReader(path);
            while (sr.Peek() >= 0) 
                Console.WriteLine(sr.ReadLine());
Run Code Online (Sandbox Code Playgroud)

c# using-statement

2
推荐指数
1
解决办法
3468
查看次数

避免在c#中使用`using`关键字进行多次处理的最佳做法

当变量是IDisposable时,我们有using关键字来管理处理.但是,如果我们在方法中返回值,那么我们应该有using两次吗?

StringContent stringToStringContent(string str)
{
    using (StringContent content = new StringContent(str))
    {
        return content;
    }
}

void logStringContent()
{
    using (StringContent content = stringToStringContent("test"))
    {
        Debug.WriteLine(content.ToString());
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面这个例子中,我只有1 new但我有2个using相同的东西.所以我觉得它不平衡.是否更好:

a)保持两者using,语言/编译器知道它的工作,以避免双重处置?

b)只保留usingnew一起,而在其他情况下,没有必要?:

void logStringContent()
{
    StringContent content = stringToStringContent("test");
    Debug.WriteLine(content.ToString());
    return;
}
Run Code Online (Sandbox Code Playgroud)

c)只有using在你不回来时才保留,并且在你返回时不需要保留?:

StringContent stringToStringContent(string str)
{
    return new StringContent(str);
}
Run Code Online (Sandbox Code Playgroud)

我唯一能感觉到的是b)不是正确的答案,因为它不适用于此处描述的问题:.NET HttpClient在多次请求后挂起(除非Fiddler处于活动状态)

c# idisposable using-statement windows-store-apps

2
推荐指数
1
解决办法
339
查看次数