标签: using

使用块Vs功能块

我想知道哪个是关于内存管理的更好方法

随着使用

 public void AddUser(User user)
        {
            using (var myentities = new MyEntities())
            {
                myentities .AddTotblUsers(user);
                myentities .SaveChanges();
            }
        }
Run Code Online (Sandbox Code Playgroud)

使用

public void AddUser(User user)
            {
                var myentities = new MyEntities();

                myentities .AddTotblUsers(user);
                myentities .SaveChanges();

            }
Run Code Online (Sandbox Code Playgroud)

哪一个从内存中删除第一个对象?第一,第二或两者相同?

c# memory-management using

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

使用HttpClient.PostAsJsonAsync发布标量数据类型

我正在使用HttpClient调用ASP .Net Web API并成功调用操作.此外,我也可以将自定义对象发布到操作中.

现在我面临的问题是,无法发布标量数据类型,如Integer,String等...

下面是我的控制器和调用操作的应用程序代码

//测试调用的应用程序

[Test]
        public void RemoveCategory()
        {
            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage();

            HttpResponseMessage response = client.PostAsJsonAsync<string>("http://localhost:49931/api/Supplier/RemoveCategory/", "9").Result;

            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
        }
Run Code Online (Sandbox Code Playgroud)

// Web API中的控制器和操作

public class SupplierController : ApiController
   {
    NorthwindEntities context = new NorthwindEntities();

    [HttpPost]
    public HttpResponseMessage RemoveCategory(string CategoryID)
    {
    try
    {
    int CatId= Convert.ToInt32(CategoryID);
    var category = context.Categories.Where(c => c.CategoryID == CatId).FirstOrDefault();
    if (category != null)
    {
    context.Categories.DeleteObject(category);
    context.SaveChanges();
    return Request.CreateResponse(HttpStatusCode.OK, "Delete successfully CategoryID = "     +     CategoryID);
    }
    else …
Run Code Online (Sandbox Code Playgroud)

using http-post dotnet-httpclient

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

何时使用Dispose或何时使用Using

我最近遇到过Dispose方法必须在C#程序中进行硬编码的情况.否则,电子邮件中使用的文件将"永久"锁定,甚至进程管理器也无法告诉我锁定它的人/锁定了什么.我不得不使用Unlocker Assistant强制删除文件,但我担心现在我在服务器上留下了一些已分配的内存块.

我指的代码是这样的:

MailMessage mail = new MailMessage();
mail.From = new MailAddress("reception@domain.com", "###");
mail.Subject = "Workplace Feedback Form";
Attachment file = new Attachment(uniqueFileName);
mail.Attachments.Add(file);
mail.IsBodyHtml = true;
mail.CC.Add("somebody@domain.com");
mail.Body = "Please open the attached Workplace Feedback form....";

//send it
SendMail(mail, fldEmail.ToString());
Run Code Online (Sandbox Code Playgroud)

上面的代码使文件不uniqueFileName被Attachment句柄锁定,我无法删除它,因为这段代码是从客户端机器(而不是从服务器本身)运行的,所以无法找到该文件的句柄.

在我强制删除文件之后,我从另一个论坛发现我应该有Disposed of Attachment对象.

所以我在发送电子邮件后添加了这些代码行...

//dispose of the attachment handle to the file for emailing, 
//otherwise it won't allow the next line to work.
file.Dispose(); 

mail.Dispose(); //dispose of the email object itself, but …
Run Code Online (Sandbox Code Playgroud)

c# asp.net dispose using handles

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

使用{...}和new来实例化C#中的匿名类型

我最近在Smarterer尝试了C#的技能测试.

我遇到一个问题,说明以下哪一项可用于在C#中创建一个匿名类型(类似的东西).

我选择了"没有这些"(我不记得其他选项,因为基于时间的测试只有10秒).

一旦我给出答案,它说这{...}是正确的答案.

所以我想这样的事情:

var someVariableName = new {...}; 创建匿名类型.

我很惊讶地看到这一点并且有点笨拙,但却找不到类似的东西.

问题:在使用{...}关键字或运算符实例化时,是否有任何方法可以创建匿名类型而不声明其类型?或问题的正确答案是不是"正确"?

dynamic如果我没有错,可以使用关键字来完成.

c# variables using anonymous-types

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

C++"......没有命名类型"

我一直在尝试定义一个类方法,它使用在类命名空间中声明的返回类型:

template<class T, int SIZE>
class SomeList{

public:

    class SomeListIterator{
        //...
    };

    using iterator = SomeListIterator;

    iterator begin() const;

};

template<class T, int SIZE>
iterator SomeList<T,SIZE>::begin() const {
    //...
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译代码时,我收到此错误:

Building file: ../SomeList.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"SomeList.d" -MT"SomeList.d" -o "SomeList.o" "../SomeList.cpp"
../SomeList.cpp:17:1: error: ‘iterator’ does not name a type
 iterator SomeList<T,SIZE>::begin() const {
 ^
make: *** [SomeList.o] Error 1
Run Code Online (Sandbox Code Playgroud)

我也尝试定义这样的方法:

template<class T, int SIZE>
SomeList::iterator SomeList<T,SIZE>::begin() const {
    //... …
Run Code Online (Sandbox Code Playgroud)

c++ gcc templates using

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

如何使用Activator.CreateInstance将泛型类型实例化为using块的一部分?

我想要实现的是将以下方法转换为更通用的方法:

    private Task<TestResult> SpecificServiceWarmUp(string serviceEndPoint)
    {
        return Task<TestResult>.Factory.StartNew(() =>
        {

            using (var service = new MySpecificClient(serviceEndPoint))
            {
                // do some stuff with specific client
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

更通用的版本看起来像:

    private Task<TestResult> GenericServiceWarmUp<TService>(string serviceEndPoint)
    {
        return Task<TestResult>.Factory.StartNew(() =>
        {

            using (/* instance of TService */)
            {
                // do some stuff with generic client
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

我不知道的是如何告诉usingActivator用于创建泛型类型的实例.这可能吗?如果是这样,我该怎么做?

c# using activator

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

为什么在c ++语言中使用命名空间std是必须的?

这是一个简单的程序,我的问题是要知道为什么使用命名空间std是必须的?为什么不使用这个程序就不遵守程序?

#include <iostream>

using namespace std;

int main(){

    int a , b , c , d;

    cout << "Enter First Value" <<endl;
    cin >> a;

    cout << "Enter Second Value" <<endl;
    cin >> b;

    cout << "Enter 1 to add values" << endl  << "Enter 2 to subtract values" <<endl  <<"Enter 3 to multiply values" <<endl ;
    cin >> c;

    if (c == 1){    
        d = a + b;
        cout << "After Adding your answer is " << d << …
Run Code Online (Sandbox Code Playgroud)

c++ using

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

为什么在StreamReader.Read周围使用using(){}允许之后删除文件?

所以我正在为学校项目尝试Windows表单并继续遇到错误:

System.IO.IOException('进程无法访问文件'C:\ XXXX\YYYY.txt',因为它正由另一个进程使用.'

当试图File.Delete(path);通过button_click事件删除文件()时.

事实证明,当我改变以下方法时:

private void updateTxt(){
  String tempStore = "";
  iDLbl1.Text = "ID:" + id;//iDLbl1 is ID Label 1
  try
  {
      StreamReader Reader = new StreamReader(path);
      while (!Reader.EndOfStream)
        { tempStore += Reader.ReadLine() + "\n"; }
  }
  catch { noIDLbl.Visible = true; }
  rTxtBox.Text = tempStore;//rTxtBox is Rich Text Box
} 
Run Code Online (Sandbox Code Playgroud)

private void updateTxt(){
    String tempStore = "";
    iDLbl1.Text = "ID:" + id;//iDLbl1 is ID Label 1
    try
    {
        using(StreamReader Reader = new StreamReader(path)) …
Run Code Online (Sandbox Code Playgroud)

c# using streamreader winforms system.io.file

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

Compactify C++函数调用语法

我想减少引用函数所需的语法量,并且想知道是否有办法做类似的事情:

(不可编译)

using pushToLastUsed = mSomeLongStackFIFOObject.push_back;
// or
auto pushToLastUsed = mSomeLongStackFIFOObject.push_back;
Run Code Online (Sandbox Code Playgroud)

然后我可以这样:

pushToLastUsed(10);
Run Code Online (Sandbox Code Playgroud)

代替:

mSomeLongStackFIFOObject.push_back(10);
Run Code Online (Sandbox Code Playgroud)

当然我可以制作一个像:

#define pushToLastUsed mSomeLongStackFIFOObject.push_back

// some code using it here

#undef pushToLastUsed
Run Code Online (Sandbox Code Playgroud)

但我不想使用宏.

c++ using

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

C#8理解使用语法

我有下一个方法:

public async Task<IEnumerable<Quote>> GetQuotesAsync()
{
    using var connection = new SqlConnection(_connectionString);

    var allQuotes = await connection.QueryAsync<Quote>(@"SELECT [Symbol], [Bid], [Ask], [Digits] FROM [QuoteEngine].[RealtimeData]");

    return allQuotes;
}
Run Code Online (Sandbox Code Playgroud)

一切都很好,也很清楚,连接将放在示波器的末尾。

但是resharper建议将其更改为:

public async Task<IEnumerable<Quote>> GetQuotesAsync()
{
    await using var connection = new SqlConnection(_connectionString);

    var allQuotes = await connection.QueryAsync<Quote>(@"SELECT [Symbol], [Bid], [Ask], [Digits] FROM [QuoteEngine].[RealtimeData]");

    return allQuotes;
}
Run Code Online (Sandbox Code Playgroud)

它在使用前增加了等待,并且代码已成功编译。这是什么意思,什么时候需要做?

c# resharper using async-await

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