为什么C#不允许将变量从using块传递给函数作为ref或out?
这是我的代码:
using (Form s = new Form())
{
doSomthing(ref s);
}
Run Code Online (Sandbox Code Playgroud)
函数在使用块结束之前结束,为什么C#不允许我s作为ref或out参数传递?
我正在浏览WildMagic 5引擎(www.geometrictools.com),其中Vector <>类继承自Tuple <>类,该类具有特定大小的数组,名为mTuple[](由模板参数设置).到目前为止这么好,没什么特别的.但是在Vector类中,我看到以下内容:
protected:
using Tuple<4,Real>::mTuple;
Run Code Online (Sandbox Code Playgroud)
现在我知道该using关键字用于正确继承重载方法.在这种情况下,我总是假设变量可用于派生类而无需键入上面的代码.以上是必要的吗?或者只是为了让事情更清楚?
我正在尝试阅读我编译的C#代码.
这是我的代码:
using(OleDbCommand insertCommand = new OleDbCommand("...", connection))
{
// do super stuff
}
Run Code Online (Sandbox Code Playgroud)
但!
我们都知道使用被转换为:
{
OleDbCommand insertCommand = new OleDbCommand("...", connection)
try
{
//do super stuff
}
finally
{
if(insertCommand != null)
((IDisposable)insertCommand).Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
(因为OleDbCommand是一个引用类型).
但是当我反编译我的程序集(用.NET 2.0编译)时,我在Resharper中得到了这个:
try
{
insertCommand = new OleDbCommand("", connection);
Label_0017:
try
{
//do super stuff
}
finally
{
Label_0111:
if ((insertCommand == null) != null)
{
goto Label_0122;
}
insertCommand.Dispose();
Label_0122:;
}
Run Code Online (Sandbox Code Playgroud)
我在说这句话:if ((insertCommand == null) != null).
假设insertCommand为null.然后第一部分返回true.(true …
作为System.Diagnostics.Process继承来自Component哪个实现IDisposable,我应该总是创建一个Process带using块吗?
例如,这......
using (var process = new Process())
{
process.StartInfo.FileName = "some process.exe";
process.Start();
process.WaitForExit();
}
Run Code Online (Sandbox Code Playgroud)
......而不是这个:
var process = new Process
{
StartInfo = { FileName = "some process.exe" }
};
process.Start();
process.WaitForExit();
Run Code Online (Sandbox Code Playgroud)
我问,因为我很少见到Process出现在using街区; 例如MSDN页面对Process不使用它.使用对象初始化程序也很有帮助.
如果我应该使用它,那么我应该去"改造"它到我现有的代码库吗?
如果没有这样做会有什么后果?(假设WaitForExit()在每种情况下都被正确调用.)
我有一个代码块如下,我使用3个嵌套using块.
我发现使用try finally块我可以避免这种情况但是如果有两个以上的使用语句,那么最好的方法是什么?
private FileStream fileStream = null;
private Document document = null;
private PdfWriter pdfWriter = null;
using (fileStream = new FileStream("ABC.pdf", FileMode.Create))
{
using (document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom))
{
using (pdfWriter = PdfWriter.GetInstance(document, fileStream))
{
document.AddAuthor(metaInformation["author"]);
document.AddCreator(metaInformation["creator"]);
document.AddKeywords("Report Generation using I Text");
document.AddSubject("Document subject");
document.AddTitle("The document title");
}
}
}
Run Code Online (Sandbox Code Playgroud) 时间再次吸引更多的思想.
我遇到了一个非常奇怪的现象.正如标题所述,我在尝试创建EF ObjectContext时遇到NullReferenceException,但是如果我在Using语句中创建上下文,我只会得到异常.我尝试了各种不同的方式,但总是一样.当然,这是直到昨天才能正常工作的代码.昨天早上我的Windows Update运行可能是相关的.
无论如何...
如果我试试这个
using (var context = new Entities(Env.Instance.Connection))
{
//do a bunch of EF stuff
}
Run Code Online (Sandbox Code Playgroud)
我在创建ObjectContext时得到NullReferenceException.这里的Env.Instance.Connection是在程序的早期创建的EntityConnection.我已经介入以确保实例和EntityConnection都存在.
如果我这样做的话
var context = new Entities(Env.Instance.Connection);
//do a bunch of EF stuff
context.Dispose();
Run Code Online (Sandbox Code Playgroud)
一切正常.
我试过了
using (var context = new Entities(Env.Instance.ConnectionName)) //the name of a connection string in my App.Config
{
//do a bunch of EF stuff
}
Run Code Online (Sandbox Code Playgroud)
我试过了
using (var context = new Entities(Env.Instance.ConnectionString)) //the actual connection string
{
//do a bunch of EF stuff
}
Run Code Online (Sandbox Code Playgroud)
我甚至试过了
using …Run Code Online (Sandbox Code Playgroud) c# entity-framework using-statement nullreferenceexception objectcontext
我正在尝试在C#中使用Reflection.Emit来发出一个using (x) { ... }块.
在我处于代码中的时候,我需要获取堆栈的当前顶部,这是一个实现IDisposable的对象,将其存储在局部变量中,在该变量上实现一个使用块,然后在其中添加更多代码(我可以处理最后一部分.)
这是我尝试编译并在Reflector中查看的C#代码示例:
public void Test()
{
TestDisposable disposable = new TestDisposable();
using (disposable)
{
throw new Exception("Test");
}
}
Run Code Online (Sandbox Code Playgroud)
这在Reflector中看起来像这样:
.method public hidebysig instance void Test() cil managed
{
.maxstack 2
.locals init (
[0] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable disposable,
[1] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable CS$3$0000,
[2] bool CS$4$0001)
L_0000: nop
L_0001: newobj instance void LVK.Reflection.Tests.UsingConstructTests/TestDisposable::.ctor()
L_0006: stloc.0
L_0007: ldloc.0
L_0008: stloc.1
L_0009: nop
L_000a: ldstr "Test"
L_000f: newobj instance void [mscorlib]System.Exception::.ctor(string)
L_0014: throw
L_0015: ldloc.1
L_0016: …Run Code Online (Sandbox Code Playgroud) 这是否可以使用using语句C#SQL?
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Run Code Online (Sandbox Code Playgroud)
如果打开连接时出错,该怎么办?
using语句是try,最后是
no catch
因此,如果我抓到外面的使用支架,捕获会捕获连接打开错误吗?
如果没有,如何使用using上面显示的语句实现这一点?
我知道我之前提过了一个相关的问题.我只是想到了另一个想法.
using (SqlConnection conn = new SqlConnection('blah blah'))
{
using(SqlCommand cmd = new SqlCommand(sqlStatement, conn))
{
conn.open();
// *** do I need to put this in using as well? ***
SqlDataReader dr = cmd.ExecuteReader()
{
While(dr.Read())
{
//read here
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
参数是:由于SqlDataReader dr对象不是一个新的对象,如连接或命令对象,它只是一个指向cmd.ExecuteReader()方法的引用,我是否需要将阅读器放在一个using.(现在基于我以前的帖子,我的理解是任何使用的对象IDisposable需要放入using,并SQLDataReader继承IDisposable,所以我需要把它.我的判断是否正确?)我只是困惑,因为它不是一个新的对象,它会在处理一个只是命令的引用指针的对象时引起任何问题吗?
非常感谢
给定一种方法
public static bool Connection.TryCreate(out Connection connection) {}
Run Code Online (Sandbox Code Playgroud)
还有一段调用代码:
Connection connection;
if (!Connection.TryCreate(out connection))
// handle failure gracefully.
/*
* work with connection
*
* …
*
*/
connection.Dispose();
Run Code Online (Sandbox Code Playgroud)
我bool.TryParse和朋友使用相同的模式,即TryCreate返回操作是否成功.
我意识到using()变量需要在其块内是只读的,但有没有办法将上面变成一个using() {}块(TryCreate只设置一次),如下所示:
using (Connection connection)
{
if (!Connection.TryCreate(out connection))
// this would leave the using() block prematurely
/*
* work with sconnection
*
* …
*
*/
}
Run Code Online (Sandbox Code Playgroud)
(这不编译:
错误CS1657:无法将'connection'作为ref或out参数传递,因为它是'using variable'
)
using-statement ×10
c# ×9
.net ×2
.net-3.5 ×1
c#-2.0 ×1
c++ ×1
coding-style ×1
dispose ×1
idisposable ×1
ilgenerator ×1
inheritance ×1
process ×1
sql ×1