根据MSDN中==运营商的文档,
对于预定义的值类型,如果操作数的值相等,则相等运算符(==)返回true,否则返回false.对于除string之外的引用类型,如果其两个操作数引用同一对象,则==返回true.对于字符串类型,==比较字符串的值.用户定义的值类型可以重载==运算符(请参阅运算符).用户定义的引用类型也是如此,尽管 默认情况下==的行为与上述预定义和用户定义的引用类型相同.
那么为什么这段代码片段无法编译呢?
bool Compare<T>(T x, T y) { return x == y; }
Run Code Online (Sandbox Code Playgroud)
我得到错误运算符'=='不能应用于'T'和'T'类型的操作数.我想知道为什么,因为据我所知,==运算符是针对所有类型预定义的?
编辑:谢谢大家.起初我没有注意到该声明仅涉及引用类型.我还认为为所有值类型提供了逐位比较,我现在知道这是不正确的.
但是,如果我使用引用类型,==操作符是否会使用预定义的引用比较,或者如果类型定义了一个,它是否会使用运算符的重载版本?
编辑2:通过反复试验,我们了解到==操作员在使用不受限制的泛型类型时将使用预定义的参考比较.实际上,编译器将使用它可以为限制类型参数找到的最佳方法,但不会再看了.例如,true即使Test.test<B>(new B(), new B())被调用,下面的代码也会始终打印:
class A { public static bool operator==(A x, A y) { return true; } }
class B : A { public static bool operator==(B x, B y) { return false; } }
class Test { void test<T>(T a, T …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,有时需要在一次操作中将10,000行或更多行保存到数据库中.我发现简单地迭代并一次添加一个项目可能需要花费半个多小时.
但是,如果我禁用AutoDetectChangesEnabled它需要约5秒(这正是我想要的)
我正在尝试向DbSet创建一个名为"AddRange"的扩展方法,该方法将禁用AutoDetectChangesEnabled,然后在完成时重新启用它.
public static void AddRange<TEntity>(this DbSet<TEntity> set, DbContext con, IEnumerable<TEntity> items) where TEntity : class
{
// Disable auto detect changes for speed
var detectChanges = con.Configuration.AutoDetectChangesEnabled;
try
{
con.Configuration.AutoDetectChangesEnabled = false;
foreach (var item in items)
{
set.Add(item);
}
}
finally
{
con.Configuration.AutoDetectChangesEnabled = detectChanges;
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是:有没有办法从DbSet获取DbContext?我不喜欢把它作为参数 - 感觉它应该是不必要的.
使用实体框架代码首先,我有类似的东西:
public class Foo
{
public int Id { get; set; }
public List<Bar> Bars { get; set; }
}
Foo foo = (from f in ctx.Foos.Include("Bars") where f.Id == 42 select f).Single();
// At this point foo.Bars is populated
ctx.Entry(foo).State = EntityState.Detached;
// At this point foo.Bars is an empty List
Run Code Online (Sandbox Code Playgroud)
为什么分离一个对象导致它的属性public List<string> Bars(明确且成功地包含在内)被清空?
分离可能具有许多属性的对象的正确过程是什么?