相关疑难解决方法(0)

你在C#或.NET中看到的最奇怪的角落是什么?

我收集了一些角落案例和脑筋急转弯,并且总是希望听到更多.该页面仅涵盖C#语言位和bobs,但我也发现核心.NET的东西也很有趣.例如,这是一个不在页面上,但我觉得不可思议的:

string x = new string(new char[0]);
string y = new string(new char[0]);
Console.WriteLine(object.ReferenceEquals(x, y));
Run Code Online (Sandbox Code Playgroud)

我希望打印False - 毕竟,"new"(带引用类型)总是会创建一个新对象,不是吗?C#和CLI的规范都表明它应该.好吧,不是在这种特殊情况下.它打印True,并在我测试过的每个版本的框架上完成.(我没有在Mono上尝试过,诚然......)

需要明确的是,这只是我正在寻找的那种事情的一个例子 - 我并不是特别想要讨论这种奇怪的事情.(它与正常的字符串实习不同;特别是,当调用构造函数时,通常不会发生字符串实习.)我真的要求类似的奇怪行为.

还有其他宝石潜伏在那里吗?

.net c#

322
推荐指数
27
解决办法
12万
查看次数

为什么尝试/最终而不是"使用"语句有助于避免竞争条件?

此问题涉及另一个帖子中的评论:取消实体框架查询

为清楚起见,我将从那里重现代码示例:

    var thread = new Thread((param) =>
    {
        var currentString = param as string;

        if (currentString == null)
        {
            // TODO OMG exception
            throw new Exception();
        }

        AdventureWorks2008R2Entities entities = null;
        try // Don't use using because it can cause race condition
        {
            entities = new AdventureWorks2008R2Entities();

            ObjectQuery<Person> query = entities.People
                .Include("Password")
                .Include("PersonPhone")
                .Include("EmailAddress")
                .Include("BusinessEntity")
                .Include("BusinessEntityContact");
            // Improves performance of readonly query where
            // objects do not have to be tracked by context
            // Edit: But it doesn't …
Run Code Online (Sandbox Code Playgroud)

.net c# asynchronous entity-framework race-condition

24
推荐指数
2
解决办法
1999
查看次数

C#处理对象

我知道当你有以下代码时,在StreamReader对象上调用Dispose()方法:

//Sample 1
using (StreamReader sr1 = new StreamReader(@"C:\Data.txt"))
{
    string s1 = sr1.ReadToEnd();
    //Do something with s1...
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您编写这样的代码(示例2),Dispose()方法也会被调用吗?

//Sample 2
StreamReader sr2 = new StreamReader(@"C:\Data.txt");
using (sr2)
{
    string s2 = sr2.ReadToEnd();
    //Do something with s2...
}
Run Code Online (Sandbox Code Playgroud)

c# dispose idisposable

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