小编HuB*_*eZa的帖子

内部System.Linq.Set <T> vs public System.Collections.Generic.HashSet <T>

Linq.Enumerable课程中查看这段代码:

static IEnumerable<TSource> DistinctIterator<TSource>(IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) {
        Set<TSource> set = new Set<TSource>(comparer);
        foreach (TSource element in source)
            if (set.Add(element)) yield return element; 
    }
Run Code Online (Sandbox Code Playgroud)

为什么微软的人决定使用这种内部实现Set而不是常规HashSet?如果它以任何方式更好,为什么不将它暴露给公众?

c# linq hashset

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

EF Code第一个无效列名"CategoryCategoryID"

有一个名为Northwind的现有数据库,带有一个webform应用程序.在运行应用程序时引发错误:'无效的列名称CategoryCategoryID'.谁帮帮我?提前致谢!!

Category.cs:

public class Category
{

    public int CategoryID { get; set; }
   // public int ID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
    public byte[] Picture { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Product.cs:

public class Product
{

    public int ProductID { get; set; }
    //public int ID { get; set; }
    public string ProductName { get; set; }
    public Decimal? UnitPrice …
Run Code Online (Sandbox Code Playgroud)

entity-framework ef-code-first

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

Visual Studio加载项,用于验证string.Format方法

string.Format是一种非常危险的方法.有很多东西可能出错,没有任何编译错误:

string.Format("{0{", text);
string.Format("{1}", text);
string.Format("(0)", text);
string.Format("{0}", text1, text2);
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种在编译时找到这个问题的方法.如果我没记错的话,Resharper发现了一些错误,但它对我的血液来说太丰富了.

c# vsx string-formatting visual-studio

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

清空目录的最佳方法是什么?

有没有办法删除指定目录的所有文件和子目录而不迭代它们?

非优雅的解决方案:

public static void EmptyDirectory(string path)
{
    if (Directory.Exists(path))
    {
        // Delete all files
        foreach (var file in Directory.GetFiles(path))
        {
            File.Delete(file);
        }

        // Delete all folders
        foreach (var directory in Directory.GetDirectories(path))
        {
            Directory.Delete(directory, true);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# filesystems

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

在匿名方法中使用MethodInfo.GetCurrentMethod()

public static void Main(string[] args)
{
    Action a = () => Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
    a();
}
Run Code Online (Sandbox Code Playgroud)

这段代码将返回一个不起眼的字符串,如下所示:<Main>b__0.

有没有办法忽略匿名方法并获得更易读的方法名称?

.net c# reflection anonymous-methods

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

Marshal.GenerateGuidForType(Type)和Type.GUID之间有什么区别?

Type classType = typeof(SomeClass);
bool equal = Marshal.GenerateGuidForType(classType) == classType.GUID;
Run Code Online (Sandbox Code Playgroud)

我没有找到一个失败的情况.

那么为什么以及何时应该使用该Marshal方法而不是简单地获取GUID属性?

.net c# com-interop marshalling

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

自引用外键的含义是什么?

我浏览了一个遗留数据库,发现了一些引用列的外键.引用的列是主键列.

ALTER TABLE [SchemaName].[TableName]  WITH CHECK ADD  
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
Run Code Online (Sandbox Code Playgroud)

它是什么意思?

foreign-keys sql-server-2008

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

使用 OUTPUT 子句从 SELECT INSERT 语句检索原始和新的身份映射

我有一个包含两列的表:

CREATE TABLE MyTable(
  Id int IDENTITY(1,1) NOT NULL,
  Name nvarchar(100) NOT NULL);
Run Code Online (Sandbox Code Playgroud)

我想使用 SELECT INSERT 语句复制数据:

INSERT INTO MyTable (Name)
SELECT Name FROM MyTable
Run Code Online (Sandbox Code Playgroud)

这是棘手的部分 - 我想检索原始身份和新身份之间的映射表:

DECLARE @idsMap TABLE (OriginalId int, NewId int)
Run Code Online (Sandbox Code Playgroud)

我知道我应该使用OUTPUT 子句,但由于某种原因它不起作用:

INSERT INTO MyTable (Name)
OUTPUT t.Id, INSERTED.Id INTO @idsMap (OriginalId, NewId)
SELECT Name FROM MyTable t
-- Returns error The multi-part identifier "t.Id" could not be bound.
Run Code Online (Sandbox Code Playgroud)

相关问题:
SQL插入使用select可以返回多个身份吗?
可以使用表参数插入,并检索标识值吗?

sql-server output-clause select-insert

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

如何检查一系列值是否正确排序?

我有很多Action带有财产的物品long Timestamp.我想做这样的事情:

Assert.IsTrue(a1.Timestamp < a2.Timestamp < a3.Timestamp < ... < an.Timestamp);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这种语法是非法的.是否有内置方式或扩展\ LINQ \无论如何执行此操作?

请注意,它是单元测试类的目标,所以要发疯.我不关心性能,可读性等.

.net c# comparison syntactic-sugar

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

我应该使用ManualResetEvent作为锁定对象吗?

对于第一次调用,下面的方法应返回true,对于任何其他调用,返回false.

它有什么问题吗?使用重置事件进行锁定是否安全?

private ManualResetEvent _resetEvent = new ManualResetEvent(false);

public bool AmIFirst()
{
    lock (_resetEvent)
    {
        bool first = !_resetEvent.WaitOne(0);
        if (first)
            _resetEvent.Set();

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

编辑:我在评论你的评论后做了一些修改.ManualResetEvent由于以前的设计理念,我被困住了.其实我根本不需要它.

class ActionSynchronizer
{
    private Timer _expirationTimer;
    private object _locker = new object();
    private bool _executionRequired = true;

    private SomeDelegate _onExpired = delegate { };

    public ActionSynchronizer(SomeDelegate onExpired)
    {
        _onExpired = onExpired;
        expirationTimer = new Timer(OnExpired, null, 30000, Timeout.Infinite);
    }

    public bool IsExecutionRequired()
    {
        if (!_executionRequired)
            return false;

        lock (_locker)
        { …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading manualresetevent

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

IsDebugEnabled与Debug(Action <FormatMessageHandler>)

在常见的日志记录V2.0中,当LogLevel高于日志条目时,有两种方法可以避免消息评估的成本:

if (Log.IsDebugEnabled)
    Log.Debug("Debug message");
Run Code Online (Sandbox Code Playgroud)

要么

Log.Debug(a => a("Debug message"));
Run Code Online (Sandbox Code Playgroud)

哪种做法更好?有什么优点和缺点?

.net lambda logging

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

忽略异常类型的更好方法:多个catch块与类型查询

在某些情况下,我们希望忽略特定的异常类型(通常ObjectDisposedException).可以通过这两种方法实现:

try
{
    // code that throws error here:
}
catch (SpecificException) { /*ignore this*/ }
catch (Exception ex)
{
    // Handle exception, write to log...
}
Run Code Online (Sandbox Code Playgroud)

要么

try
{
    // code that throws error here:
}
catch (Exception ex)
{
    if (ex is SpecificException) { /*ignore this*/ }
    else
    {
        // Handle exception, write to log...
    }
}
Run Code Online (Sandbox Code Playgroud)

这两种方法的优点和缺点是什么(关于性能,可读性等)?

.net c# exception-handling

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

为什么使用ReaderWriterLockSlim不会使我的Dictionary线程安全?

我写了一小段代码,可以快速读取和写入多个线程的字典.我使用ReaderWriterLockSlim来保护代码,并且仍然收到了涉嫌尝试添加重复密钥的异常.

ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
Dictionary<int, int> _dict = new Dictionary<int, int>();

public SafeDictionaryTester()
{
    for (int i = 0; i < 7; i++)
    {
        _dict.Add(i, i);
    }
}

internal void Execute()
{
    for (int i = 7; i < 10000; i++)
    {
        if (i % 6 == 0)
            new Thread(new ThreadStart(delegate { Print(6); })).Start();
        else if (i % 5 == 0)
            new Thread(new ThreadStart(delegate { Print(5); })).Start();
        else if (i % 4 == 0)
            new Thread(new ThreadStart(delegate { …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading dictionary readerwriterlockslim

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