小编Car*_*rra的帖子

新锁内

我注意到外国程序员的以下代码:

private Client[] clients = new Client[0];

public CreateClients(int count)
{
    lock (clients)
    {
        clients = new Client[count];

        for(int i=0; i<count; i++)
        {
           Client[i] = new Client();//Stripped
        }
     }
 }
Run Code Online (Sandbox Code Playgroud)

这不是完全正确的代码,但我想知道这究竟是做什么的.每次调用此方法时,这会锁定一个新对象吗?

c# multithreading locking

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

号码分发

问题:我们有x个复选框,我们想要均匀地检查它们.

示例1:选择50个总共100个复选框.

[-]
[x]
[-]
[x]
...
Run Code Online (Sandbox Code Playgroud)

示例2:选择总共100个的33个复选框.

[-]
[-]
[x]
[-]
[-]
[x]
...
Run Code Online (Sandbox Code Playgroud)

示例3:选择总共100个的66个复选框:

[-]
[x]
[x]
[-]
[x]
[x]
...
Run Code Online (Sandbox Code Playgroud)

但是我们很难想出一个公式来检查代码,特别是一旦你进入11/111或类似的东西.有人有想法吗?

language-agnostic algorithm

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

C# enums - Possible to have double ids

I just noticed that you can create something like this in C#:

enum TestEnum
{
  First = 1,
  Second = 1,
  Third = 2
}

[TestMethod]
public void Test()
{
  TestEnum test = TestEnum.First;
  var en = (TestEnum) 1;//And en is now set to First
}
Run Code Online (Sandbox Code Playgroud)

We would like the enums value to be unique. Right now, I have written a unit test that checks that each value is only used once in our enum. Is there a better way …

.net c# enums unique

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

强制执行日期时间类型

我们正在编写一个可供其他团队访问的 dll。我们的要求之一是传递的每个 DateTime 都有一个 DateTimeKind.Utc。

但是,我们没有强制执行此要求,这会导致错误。所以我们想知道如何强制执行这一点。

我们有一些想法:

  • 编写一个方面来检查传递给方法的每个参数。当 Kind != UTC 时抛出异常。这可以工作,但当您传递包含 DateTime 的对象时则不起作用。

  • 使用自定义对象 UtcDateTime 更改所有日期时间。

这可能有效,但需要确保我们替换每个 DateTime 以及对日期时间的所有调用。看起来像这样:

public class UtcDateTime
{
  private DateTime _dateTime;
  public UtcDateTime(DateTime dateTime)
  {
    if(dateTime.Kind != DateTimeKind.Utc)
    {
        throw new ArgumentException();
    }
    _dateTime = dateTime;
  }
}
Run Code Online (Sandbox Code Playgroud)

有更好的方法来做到这一点吗?

.net c# datetime

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

不变的字典

我想知道我是否可以创建一个返回只读字典的属性?

例:

    private readonly Dictionary<string, IMyObject> _myDictionary;
    public Dictionary<string, IMyObject> MyDictionary
    {
        get { return _myDictionary; }
    }
Run Code Online (Sandbox Code Playgroud)

因此,不允许使用MyDictionary的人添加,删除或更改项目.有什么方法可以做到这一点?

.net c#

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

可能的NullreferenceException

Resharper显示"可能的System.NullReferenceException"警告.然而,我无法看到我如何得到一个.

public class PlaceController : PlanningControllerBase
{
    [Authorize]
    public ActionResult StartStop(int id)
    {
        if (Request != null && Request.Cookies != null && Request.Cookies["place"] != null)
        {
            if (Request.Cookies["place"].Value != null)//Possible NullReferenceException?
            {
                string placeInformation = Request.Cookies["place"].Value;//Possible NullReferenceException?
                //...
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我检查所有字段,它如何给出NullReference?使用以下内容不会显示警告:

Request.Cookies[0];//Index instead of name
Run Code Online (Sandbox Code Playgroud)

编辑:更新的代码.

c# resharper nullreferenceexception

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

提高单个Web服务的超时时间

我的Web配置如下所示:

<system.web>
    <compilation debug="false"/>
    <httpRuntime executionTimeout="90"/>
</system.web>
Run Code Online (Sandbox Code Playgroud)

这适用于大多数Web服务函数,但是一个函数的查询运行时间很长(5分钟),并且在完成之前将停止.是否可以单独为此Web服务将运行时设置为5分钟?

例如:

  MyWebServices.asmx?op=WS_LongMethod --> Timeout of 5 minutes
Run Code Online (Sandbox Code Playgroud)

我已经考虑过运行数据库查询async(fire and forget),但是通过ODBC使用sybase/oracle似乎不可能.

.net c# web-services

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

Enum上的位操作

我遇到以下问题:

  • 我想获得列集合的第一个可见AND冻结列.

我想这会做到:

DataGridViewColumnCollection dgv = myDataGridView.Columns;
dgv.GetFirstColumn(
     DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen);
Run Code Online (Sandbox Code Playgroud)
  • 是否也可以使用位掩码来获得第一个冻结的OR可见列?

c# enums bit bitwise-operators

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

强制打开文件

一个C++程序正在填充日志文件,它保留了日志文件的句柄.我想用C#程序打开这个日志文件并解析它以查看某个行是否已添加到日志文件中.

但是,如果我用C#打开日志文件,我会得到一个"这个文件被另一个进程使用"IOException.使用的代码:

using(StreamReader reader = File.OpenRead(myFile))//IOException
Run Code Online (Sandbox Code Playgroud)

C++程序用(我无法更改C++程序)打开文件:

m_hFile = tsopen(m_csFilePath, 
_O_WRONLY|_O_APPEND|_O_TRUNC|_O_CREAT|_O_BINARY,
_SH_DENYWR,
_S_IREAD | _S_IWRITE); 
Run Code Online (Sandbox Code Playgroud)

用记事本打开文件工作正常,因此应该可以打开它.我可以强制我的C#程序以只读模式打开文件吗?

c# permissions file

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

FXCop投射警告

运行FXCop时出现以下错误:

CA1800:Microsoft.Performance:'obj',一个变量,在方法'ProductsController.Details(int,int)'中被多次强制输入'Job'.缓存'as'运算符或直接强制转换的结果,以消除冗余的castclass指令

码:

        object obj = repository.GetJobOrPlace(jobId);//Returns  (object) place or (object) product

        if (obj != null)
        {
            if (obj is Job)
            {
                Job j = (Job) obj;
                Debug.WriteLine(j.Title);
            }
            else if (obj is Place)
            {
                Place p = (Place) obj;
                Debug.WriteLine(p.Title);
            }
        }
Run Code Online (Sandbox Code Playgroud)

这有什么问题?我只能看到一个演员阵容:Job j =(Job)obj.

c# fxcop

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

.Except/Yield返回内存不足异常

我使用Linq的Except语句耗尽内存.

例:

var numbers = Enumerable.Range(1, 10000000);
int i=0;
while (numbers.Any())
{
    numbers = numbers.Except(new List<int> {i++});
}
Run Code Online (Sandbox Code Playgroud)

我反编译了这个方法,这样做同样也给出了内存不足的异常.

var numbers = Enumerable.Range(1, 10000000);
int i=0;
while (numbers.Any())
{
   numbers = CustomExcept(numbers, new List<int>{i++});
}
private IEnumerable<int> CustomExcept(IEnumerable<int> numbers, IEnumerable<int> exceptionList)
{
    HashSet<int> set = new HashSet<int>();
    foreach (var i in exceptionList)
    {
        set.Add(i);
    }
    foreach (var i in numbers)
    {
        if (set.Add(i))
        {
           yield return i;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:为什么会抛出内存异常?

我希望垃圾收集器能够清理未使用的HashSet.

c# linq out-of-memory yield-return

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

以编程方式更改代码文件

我正在将我们的web服务更改为异步模型.为此,我必须改变一百多种方法.

手动执行是一个(没有吸引力的)选项.有没有办法以编程方式解析和更改多个函数/代码文件?

例:

[Webmethod]
public void MyWebservice (string parameter1, string parameter2, string parameter3)
{
  //Logic here
}
Run Code Online (Sandbox Code Playgroud)

并将其更改为:

public void InternalMyWebservice (string parameter1, string parameter2, string parameter3, AsyncCallback callback)
{
  //Logic here
}

[Webmethod]
public void BeginMyWebservice (string parameter1, string parameter2, string parameter3, AsyncCallback callback, object asyncState)
{
  //Queue InternalMyWebservice in a threadpool
}

public void EndMyWebservice(IAsyncResult asyncResult)
{
  //Set return values
}
Run Code Online (Sandbox Code Playgroud)

对于每个Web服务,我必须做的事情基本相同.将名称更改为"InternalX",添加参数并创建开始和结束方法.

.net c# code-generation

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