我知道我总是必须覆盖Equals(object)和GetHashCode()实施时IEquatable<T>.Equals(T).
但是,我不明白,为什么在某些情况下Equals(object)胜过通用Equals(T).
例如,为什么会发生以下情况?如果我声明IEquatable<T>一个接口并X为它实现一个具体的类型,那么在将这些类型的项目相互比较时,将Equals(object)调用general Hashset<X>.在其中至少一个边被强制转换为接口的所有其他情况下,Equals(T)调用正确的.
这是一个代码示例来演示:
public interface IPerson : IEquatable<IPerson> { }
//Simple example implementation of Equals (returns always true)
class Person : IPerson
{
public bool Equals(IPerson other)
{
return true;
}
public override bool Equals(object obj)
{
return true;
}
public override int GetHashCode()
{
return 0;
}
}
private static void doEqualityCompares()
{
var t1 = new Person(); …Run Code Online (Sandbox Code Playgroud) 给定一个类ThisClassShouldBeTheDataContext的实例作为视图的Datacontext
class ThisClassShouldBeTheDataContext
{
public Contacts Contacts {get;set;}
}
class Contacts
{
public IEnumerable<Person> Persons {get;set;}
public Person this[string Name]
{
get
{
var p = from i in Persons where i.Name = Name select i;
return p.First();
}
}
}
class Person
{
public string Name {get;set;}
public string PhoneNumber {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
如何绑定Contact["John"].PhoneNumber到文本框?
<TextBox Text="{Binding ?????}" />
Run Code Online (Sandbox Code Playgroud) 如果我为值类型实现接口并尝试将其转换为List的接口类型,为什么这会导致错误,而引用类型转换得很好?
这是错误:
无法将实例参数类型转换
System.Collections.Generic.List<MyValueType>为System.Collections.Generic.IEnumerable<MyInterfaceType>
我必须明确地使用该Cast<T>方法来转换它,为什么?因为IEnumerable是通过集合的只读枚举,所以对我来说没有任何意义,它不能直接转换.
以下是演示此问题的示例代码:
public interface I{}
public class T : I{}
public struct V: I{}
public void test()
{
var listT = new List<T>();
var listV = new List<V>();
var listIT = listT.ToList<I>(); //OK
var listIV = listV.ToList<I>(); //FAILS to compile, why?
var listIV2 = listV.Cast<I>().ToList(); //OK
}
Run Code Online (Sandbox Code Playgroud) 我想写一个方法,它做了一些工作,最后返回另一个方法与原始方法相同的签名.这个想法是依次处理一个字节流,而不是进入递归.通过这样称呼它:
MyDelegate executeMethod = handleFirstByte //What form should be MyDelegate?
foreach (Byte myByte in Bytes)
{
executeMethod = executeMethod(myByte); //does stuff on byte and returns the method to handle the following byte
}
Run Code Online (Sandbox Code Playgroud)
要切换方法,我想将它们分配给Func委托.但我遇到的问题是,这导致递归声明而没有终止...
Func<byte, Func<byte, <Func<byte, etc... >>>
Run Code Online (Sandbox Code Playgroud)
我不知何故在这里迷路了.我怎么能绕过那个?
我们从sqlite-net更改为sqlite.net PCL版.我们的项目与旧项目合作得很好 - 在PCL版本中,我们现在必须通过使用明确声明我们的平台.
var conn = new SQLiteConnection(new SQLitePlatformWin32(), Path.Combine(folderPath, dbName));
Run Code Online (Sandbox Code Playgroud)
但是现在,当我打电话给这一行时,我们得到一个
SQLite.Net.Platform.Win32.dll中出现'System.TypeInitializationException'类型的第一次机会异常
附加信息:"SQLite.Net.Platform.Win32.SQLiteApiWin32Internal"的类型初始化程序引发了异常.
内在的例外告诉我们
{"无法加载本机sqlite库"}
堆栈跟踪:
在SQLite.Net.Platform.Win32.SQLiteApiWin32Internal.sqlite3_open_v2(Byte [] filename,IntPtr&db,Int32标志,IntPtr zvfs)
在SQLite.Net.Platform.Win32.SQLiteApiWin32.Open(Byte [] filename,IDbHandle&db,Int32 flags,IntPtr zvfs)
在SQLite.Net.SQLiteConnection..ctor(ISQLitePlatform sqlitePlatform,String databasePath,SQLiteOpenFlags openFlags,Boolean storeDateTimeAsTicks,IBlobSerializer序列化程序,IDictionary
2 tableMappings, IDictionary2 extraTypeMappings,IContractResolver解析器)在SQLite.Net.SQLiteConnection..ctor(ISQLitePlatform sqlitePlatform,String databasePath,Boolean storeDateTimeAsTicks,IBlobSerializer serializer,IDictionary
2 tableMappings, IDictionary2 extraTypeMappings,IContractResolver resolver)
但是,sqlite3.dll位于应用程序文件夹中,它实际上可以使用unforked版本.我玩了编译x86和x64,并为Win32下载了最新的sqlite3.dll但都没有成功.我们缺少什么?
我们正在慢慢地将项目从旧的基于文件的存储(不要求)转移到tfs.我们的编码器仍然用于查找文件系统中的代码.
由于我们正在谈论每个都有某种历史的100个项目,我们必须逐一仔细地移动它们.结果是,我们将不得不使用与TFS托管文件混合的现有文件结构生存一段时间.
为了让编码人员的生活更轻松,我想在文件系统中为我们移动的每个项目创建一个快捷方式.因此开发人员可以查看项目是否已被移动,如果是,则双击以打开直接指向正确项目的TFS源代码管理资源管理器.
这可能吗?感谢您的答复.
关于下面提到的编译器错误以及如何解决它,有很多问题/解答,但是这里的问题是询问一些见解,为什么在这种情况下需要这样做。
为什么使用另一个引用的项目B的方法的重载的项目A(在其中一个重载的签名中使用项目C的对象),就要求您引用项目A的项目C,即使您从不使用来自该对象的对象也是如此。项目C?
我想这必须与使用哪种重载有关,但我想了解其背后的概念。
这是一个例子:
将每个类放在自己的程序集中。
//Put into Assembly C
public class C {}
//Put into assembly B, reference C
public class B
{
public static void Test(string param) //Simple method with one string parameter
{
}
public static void Test(C param) //Overload which uses type of assembly C
{
}
}
//Call placed in method of assembly A which uses and references only assembly B, but not C
B.Test("TestString"); // fails to compile, CS0012
Run Code Online (Sandbox Code Playgroud)
CS0012类型'C'在未引用的程序集中定义。您必须添加对程序集'C,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = …
.net c# .net-assembly overload-resolution assembly-references
我试图Login在我AccountController的MusiStore示例中基于此测试对我这样的简单方法进行单元测试.
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginArgumentsModel model)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return Ok();
}
return StatusCode(422); // Unprocessable Entity
}
Run Code Online (Sandbox Code Playgroud)
为此,我需要使用两者UserManager,SignInManager并最终迫使我使用写替代IAuthenticationHandler使用HttpAuthenticationFeature.最后的测试结果如下:
public class AccountControllerTestsFixture : IDisposable
{
public IServiceProvider BuildServiceProvider(IAuthenticationHandler handler)
{
var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();
var services = new ServiceCollection();
services.AddOptions();
services.AddDbContext<ApplicationDbContext>(b …Run Code Online (Sandbox Code Playgroud) 我有一个小项目,它使用Asp.Net核心身份框架和EF Core.一个函数调用UserManager.FindByIdAsync(id)并返回正确的对象.但是,它仅在应用程序启动后的几分钟内工作.只要服务器忙,它就可以正常工作,但只要应用程序空闲超过1-2分钟,请求就会失败.
它失败了:
*OperationCanceledException: The operation was canceled.
System.Threading.CancellationToken.ThrowOperationCanceledException()*
Run Code Online (Sandbox Code Playgroud)
stacktrace看起来像这样:
*System.Threading.CancellationToken.ThrowOperationCanceledException()
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore.FindByIdAsync(string userId, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.UserManager.FindByIdAsync(string userId)
MyProject.Areas.Admin.ControllerServices.UserService+<GetUser>d__11.MoveNext() in UserService.cs*
Run Code Online (Sandbox Code Playgroud)
我还在登录,因为其他页面工作正常.对EF的简单调用context.Users.FindAsync(new object[] { id })将按预期工作,但下一行包含FindByIdAsync将失败.
所有这些在开发环境中都很完美,当在WS 2008 R2上运行IIS的服务器上安装应用程序时会发生错误.回收应用程序池将使其再次工作,直到它再次闲置几分钟.
我注意到当'Connection id'0HL5E91K33IIQ"重置"时.正在记录,然后应用程序开始失败.在此之前,它的工作原理.
FindByIdAsync不是唯一失败的标识函数,许多其他函数失败并出现相同的错误.
我错过了什么?
我在代码上遇到设计器错误:
组件我愿意为以下内容定义属性列表:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace TestProjectForProperty.Test
{
public class MyTreeView : TreeView
{
private List<TypeDescriptorBase> _descriptorsAvailable = new List<TypeDescriptorBase>();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<TypeDescriptorBase> DescriptorsAvailable
{
get { return _descriptorsAvailable; }
set { _descriptorsAvailable = value; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
描述符本身:
using System;
namespace TestProjectForProperty.Test
{
[Serializable]
public class TypeDescriptorBase
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试在表单上使用组件并将属性表或组件的构造函数中的任何项添加到DescriptorsAvailable属性,我会收到以下错误
错误1无效的Resx文件.无法加载类型System.Collections.Generic.List`1 [[TestProjectForProperty.Test.TypeDescriptorBase,TestProjectForProperty,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]],mscorlib,Version = …
我有一个带有.NET库的项目,我用ConfuserEx进行了混淆.在保护运行期间,我收到一条警告,说明如下:
[WARN] [foo.dll] SN Key is not provided for a signed module, the output may not be working.
Run Code Online (Sandbox Code Playgroud)
事实上,该程序集使用强大的密钥名称进行签名.但是,代码似乎在没有问题的情况下运行.
这产生了两个问题:
软件文档和cli输出都没有给我一个如何包含密钥的指示.将密钥复制到与dll相同的文件夹不会解决警告.
我有一个表格,我用ShowDialog显示.我明确地为表单设置了图标:
using (frmActivation myActivationView = new frmActivation())
{
myActivationView.ShowInTaskbar = true;
myActivationView.Icon = Properties.Resources.icon;
myActivationView.ShowDialog();
}
Run Code Online (Sandbox Code Playgroud)
而且我还要把它设置在应用程序选项卡中的项目属性为这里mentionend:

即使我将ShowInTaskbar明确地设置为true,它也会显示错误的图标.

我不知道还有什么可能是它不会显示设置图标的原因?
Enum.ToString(string)不支持直接使用精度说明符X2或D5将填充应用于数值. 格式类似ToString("X")或ToString("D")已实现且记录良好.当然,我可以明确地将其转换为int之前,因此使用为int实现的格式说明符将其转换为填充字符串.
我想知道是否有一些直接支持enum的这个功能,而不需要强制转换它们.乍一看似乎很奇怪,这不是直接实现的,因为它是为int或其他数字类型完成的.但也许我错过了一些更重要的东西,这些东西可以明确地解释说它没有像枚举那样完成?
public enum Number
{
Ten = 10
}
Console.WriteLine(Number.Ten); //OK: Ten
Console.WriteLine(Number.Ten.ToString()); //OK: Ten
Console.WriteLine(Number.Ten.ToString("D")); //OK: 10
Console.WriteLine(Number.Ten.ToString("D5")); //Expected 00010 - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or
Console.WriteLine(Number.Ten.ToString("X")); //OK: 0000000A
Console.WriteLine(Number.Ten.ToString("X2")); //Expected 0A - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or "d"
Console.WriteLine(10.ToString("X2")); //OK: 0A
Console.WriteLine(10.ToString("D5")); //OK: 00010
Console.WriteLine(((int)Number.Ten).ToString("X2"));//OK: 0A
Run Code Online (Sandbox Code Playgroud)
接受答案的简短摘要:它没有明确表示,因为根据基础类型的大小,它已经被隐含地完成了.因此,如果你喜欢X2而不是X8只使用字节作为基础类型,ToString("X")并将表现得像ToString("X2").
c# ×9
.net ×3
properties ×2
asp.net ×1
asp.net-core ×1
binding ×1
c#-4.0 ×1
covariance ×1
delegates ×1
designer ×1
enums ×1
func ×1
generics ×1
icons ×1
iequatable ×1
indexer ×1
inheritance ×1
obfuscation ×1
sqlite ×1
sqlite-net ×1
tfs2010 ×1
tostring ×1
unit-testing ×1
winforms ×1
wpf ×1
xaml ×1