我正在将一些代码添加到usingC#程序的块中.我有点填充我的应用程序,以前是一个独立的现有代码体,所以我需要做一些搞乱使它适合.最终结果如下:
public class WrapperForMyOldApp
{
public static ItemThatINeed item1;
public static ItemThatINeed item2;
public WrapperForMyOldApp ()
{
item1 = new ItemThatINeed();
item2 = new ItemThatINeed();
}
public static go()
{
// some stuff that i need to do with items 1 and 2
}
}
public class MainProgram
{
.
.
.
public void MethodThatNeedsToMakeUseOfMyApp ()
{
....
using (WrapperForMyOldApp oldAPp = new WrapperForMyOldApp())
{
WrapperForMyOldApp.go();
}
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,这里的问题是:我现在是否已经削弱了使用块的效果和/或产生了任何可能对MainProgram类产生负面影响的特殊副作用?我相信Wrapper对象和它的内容将被Disposed并且执行将按预期继续,但有什么我需要注意的,我忽略了吗?
谢谢!
想一想:
StreamReader reader = null;
try
{
reader = new StreamReader(_fileName);
}
catch
{
//show error that file not found
reader.Dispose();
return false;
}
try
{
//code to read file
}
catch
{
//show error badly formed file
}
finally
{
reader.Dispose();
}
//return
Run Code Online (Sandbox Code Playgroud)
当无法打开文件时,上面的代码不起作用,因为它调用Dispose for null导致异常.
我不想使用因为我想分开打开文件和阅读它的问题.这可以通过百万种不同的渔获量实现,但我不想这样做.另外如果使用与try-finally相同,那么"隐藏Dispose"会抛出不需要的异常吗?当我需要的只是捕获异常打开它并读取异常时,这将是最好的方法吗?
谢谢和BR - 马蒂
我需要一种方法using从代码中删除所有语句并完全限定引用的代码行.例:
之前:
using System.Windows.Forms;
namespace XYZ
{
class Temp
{
public void IRFunction()
{
MessageBox.Show("Hello!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
后:
namespace XYZ
{
class Temp
{
public void IRFunction()
{
System.Windows.Forms.MessageBox.Show("Hello!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我假设解决方案也会自动回答以下问题:如何枚举符合using语句的引用名称空间,并可用于解析代码中的引用.
我发现我的代码库包含各种数据访问代码,其中我以两种不同的方式使用using语句.哪个是更好的方式,这两种方法有什么不同?在using语句中不实例化SqlConnection和SqlCommand可能引起的任何问题?忽略明显的不一致问题.
方法1:
public int SampleScalar(string query, CommandType queryType, SqlParameter[] parameters)
{
int returnValue = 0;
SqlConnection objConn = new SqlConnection(ConnString);
SqlCommand objCmd = new SqlCommand(query, objConn);
objCmd.CommandType = queryType;
if (parameters.Length > 0)
objCmd.Parameters.AddRange(parameters);
using (objConn)
{
using (objCmd)
{
objConn.Open();
try
{
returnValue = (int)objCmd.ExecuteScalar();
}
catch (SqlException e)
{
Errors.handleSqlException(e, objCmd);
throw;
}
}
}
return returnValue;
}
Run Code Online (Sandbox Code Playgroud)
方法2:
public int SampleScalar2(string query, CommandType queryType, SqlParameter[] parameters)
{
int returnValue = 0;
using (SqlConnection objConn = new SqlConnection(ConnString)) …Run Code Online (Sandbox Code Playgroud) 这有效,但我想使用"using"关键字.
Stream st = null;
st = request.GetRequestStream();
st.Write(bytes, 0, bytes.Length);
st.Close();
Run Code Online (Sandbox Code Playgroud)
我如何在这里使用关键字"使用"?
使用(Stream st = ...
这是我的情况.
我是这样做的:
using (StreamReader srReader = new StreamReader(strInputFile))
{
// loop until EOF
while ((strCurrentLine = srReader.ReadLine()) != null)
{
// "process" strCurrentLine...
// write the "processed" strCurrentLine to a new text file
using (StreamWriter sw = new StreamWriter(strFullOutputPathFileName, false))
{
// write strCurrentLine to the new file
sw.WriteLine("stuff...");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的经理告诉我,使用using像我在循环中的语句将极大地阻碍性能.原因是因为StreamWriter实例将在循环时创建多次.所以,如果我循环1000次,我会有1000个StreamWriter物体实例,这可能严重阻碍性能.
这是真的?另外,我的方法是否是实现此目的的最佳方法?
我写了一个小using语句,可以轻松访问可变参数模板参数包的类型.
template<size_t index, typename args...>
using get = std::tuple_element<index, std::tuple<args...>>::type;
Run Code Online (Sandbox Code Playgroud)
但是用clang(3.5.0)或gcc(4.9.0)编译它会失败.这是clang的错误输出:
error: expected ',' or '>' in template-parameter-list template<size_t index, typename args...>
^
Run Code Online (Sandbox Code Playgroud)
该using语句是否与可变参数模板不可组合?或者我做错了什么?
//C#
using (System.IO.StreamWriter writer =
new System.IO.StreamWriter("me00.txt", true))
{
writer.WriteLine("Hey"); //saved
}
System.IO.StreamWriter writer02 = new System.IO.StreamWriter("me01.txt", true);
writer02.WriteLine("Now hey x2"); //not saved
Run Code Online (Sandbox Code Playgroud)
创建了文件me00.txt和me01.txt,但只保存了第一个文件的内容.
me00.txt会排队嘿.me01.txt将是一个空的txt文件; "现在嘿x2"没有保存.
关键词"使用"做了什么来引起这种观察?
我有一个类,有很多静态方法来管理数据库操作.所有方法都遵循以下模式:
try
{
using(var trans = new TransactionScope())
{
using(var context = new DBContext())
{
. . . // method body
}
trans.Complete();
}
}
catch(Excepcion ex)
{
Log.Error(ex.Message);
if (ex.InnerException != null)
Log.Error(ex.InnerException.Message);
}
Run Code Online (Sandbox Code Playgroud)
如何重构我的代码,以便不需要在每个方法中编写这个结构?
编辑实施Jon的回复.
public static T TransactionalOperation<T>(Func<DBContext, T> databaseAction)
{
T retVal = default(T);
try
{
using (var trans = new TransactionScope())
{
using (var context = new DBContext())
{
if (databaseAction != null)
retVal = databaseAction(context);
}
trans.Complete();
}
catch (Exception ex)
{
Log.Error(ex.ToString());
} …Run Code Online (Sandbox Code Playgroud) 我有一个类成员变量_stream,它是一个FileStream.这个变量在构造函数中初始化,需要坚持到我完成这个类.我有另一个类,每次需要写入文件时都会引发一个事件.在我的主类中,我有一个执行实际写作的事件处理程序.我在这个问题中尝试了以下代码:
void MyEventHandler(string message)
{
using (_stream)
using (StreamWriter s = new StreamWriter(_stream))
s.WriteLine(message);
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为在我完成它之前using处置了我FileStream.我应该做什么呢?
using ×10
c# ×8
file-io ×2
streamwriter ×2
ado.net ×1
c#-2.0 ×1
c++ ×1
c++11 ×1
dispose ×1
events ×1
filestream ×1
idisposable ×1
resolve ×1
streamreader ×1
templates ×1
text ×1
try-catch ×1