假设我想将Double转换x为Decimal y.有很多方法可以做到这一点:
1. var y = Convert.ToDecimal(x); // Dim y = Convert.ToDecimal(x)
2. var y = new Decimal(x); // Dim y = new Decimal(x)
3. var y = (decimal)x; // Dim y = CType(x, Decimal)
4. -- no C# equivalent -- // Dim y = CDec(x)
Run Code Online (Sandbox Code Playgroud)
从功能上讲,上述所有内容都做同样的事情(据我所知).除了个人品味和风格之外,还有一个特别的理由选择一种选择吗?
编辑:这是通过编译Release配置中的三个C#选项生成的IL:
1. call valuetype [mscorlib]System.Decimal [mscorlib]System.Convert::ToDecimal(float64)
--> which calls System.Decimal::op_Explicit(float64)
--> which calls System.Decimal::.ctor(float64)
2. newobj instance void [mscorlib]System.Decimal::.ctor(float64)
3. call valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Explicit(float64)
--> which calls …Run Code Online (Sandbox Code Playgroud) 我的问题是如何在c#中处理sql异常,无论如何都要检查从数据访问层抛出什么样的sql异常?例如,如果db抛出唯一约束异常或外键异常,有没有办法从c#中捕获它?您使用这些数据库异常的异常处理模式是什么?
在我们的SQL Server 2005数据库中(使用带有DBCC FREEPROCCACHE和的
Management Studio进行测试DBCC DROPCLEANBUFFERS),以下语句很快(~0.2s编译时间,~0.1s执行时间):
SELECT ... FROM ... WHERE a = 1 AND b = '' ...
Run Code Online (Sandbox Code Playgroud)
但是,以下语句很慢(编译时间约为0.2秒,执行时间为7-11秒):
exec sp_executesql N'SELECT ... FROM ... WHERE a = @a AND b = @b ...', N'@a int, @b nvarchar(4000), ...', @a=1, @b=N'', ...
Run Code Online (Sandbox Code Playgroud)
SQL Server选择不同的执行计划,尽管查询是相同的.这是有道理的,因为在第一种情况下,SQL Server有实际价值a,b以及所有可用的其他参数和可使用的统计数据来创建一个更好的计划.显然,参数的具体值的查询计划要比通用的好得多,并且肯定超过任何"查询计划缓存"性能优势.
现在我的问题是:ADO.NET似乎总是在执行参数化查询时使用第二个选项(sp_executesql),这通常是有意义的(查询计划缓存等).然而,在我们的案例中,这会导致性能下降.那么,有没有办法
sp_executesql(即SQL Server查询分析器将实际参数值考虑在内的东西)或sp_executesql 将参数值考虑在内?请不要告诉我,我必须回到丑陋,陈旧,危险sql = "WHERE b = " + quoteAndEscape(parameterB) …
在客户,我们的一个WPF应用程序开始挂起.当尝试用最小的工作示例重现问题时,我发现即使是最基本的(非平凡的)WPF应用程序也会挂在该机器上.
示例A:在Visual Studio 2008中创建一个新的C#WPF项目.不做任何更改,编译它并在客户的计算机上运行它.它会运行.
示例B:获取示例A,并将TextBlock添加到主窗体Window1:
<Window ...>
<Grid>
<TextBlock>Test</TextBlock>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
编译应用程序并在客户的计算机上运行它.它将挂起:标题栏和窗口边框是可见的,内部是透明的,窗口不会对任何东西做出反应(无法移动或关闭).必须使用任务管理器关闭应用程序.
显然,该客户的WPF已被破坏.这是一个已知问题,即之前是否有人遇到它并且已经知道如何解决它(例如重新安装.net 3.5 SP1等)?
开发机器是W7SP1,客户的机器是XP(可能是SP3,没检查).
我的应用程序包含对外部库(SQL Server管理对象)的引用.显然,如果运行时系统中不存在该库,则只要没有调用使用此库中的类的方法,应用程序仍然可以工作.
问题1:这是指定行为还是CLR加载库的方式(幸运)副作用?
要检测引用是否可访问,我目前使用如下代码:
Function IsLibraryAvailable() As Boolean
Try
TestMethod()
Catch ex As FileNotFoundException
Return False
End Try
Return True
End Function
Sub TestMethod()
Dim srv As New Smo.Server() ' Try to create an object in the library
End Sub
Run Code Online (Sandbox Code Playgroud)
它有效,但似乎很难看.注意如果TestMethod的是一个单独的方法,它才能正常运行,否则异常将在抛出开头的IsLibraryAvailable(在try-catch之前,即使对象实例化try-catch块内occurrs).
问题2:有更好的选择吗?
特别是,我担心函数内联等优化可能会阻止我的代码工作.
为什么以下结果都是真正的if子句,即使文本框是空的,甚至没有触及回发?:
<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>
<%
if (Request.Form["name"] != null) // Prints out "Name OK" on postback.
{
Response.Write("<br/>");
Response.Write("Name OK");
}
%>
Run Code Online (Sandbox Code Playgroud)
文本框实际上是否在回发中包含空字符串("")?
为什么以下结果导致第一页上的true if子句加载而不是回发?:
<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>
<%
if (Request.Form["name"] != "") // Prints out "Name OK" on first page load, but not on postback.
{
Response.Write("<br/>");
Response.Write("Name OK");
}
%>
Run Code Online (Sandbox Code Playgroud)
为了获得成功和预期的结果,我必须使用以下内容:
<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>
<%
if (Request.Form["name"] …Run Code Online (Sandbox Code Playgroud) 是否有令人信服的理由在常规枚举的HashSet上使用Flags枚举(即位掩码)?据我所知,两者都解决了同样的问题:
enum Color { Red, Green, Blue }
[Flags()]
enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 }
void Test()
{
// initialization
var supportedColors1 = new HashSet<Color> { Color.Red, Color.Green };
var supportedColors2 = Colors.Red | Colors.Green;
// comparison
if (supportedColors1.Contains(Color.Green)) { /* ... */ }
if ((supportedColors2 & Colors.Green) != 0) { /* ... */ }
// manipulation
supportedColors1.Remove(Color.Red);
supportedColors2 ^= Colors.Red; // if I'm sure that Red is contained
supportedColors2 …Run Code Online (Sandbox Code Playgroud) IEnumerable不保证枚举两次会产生相同的结果.实际上,创建一个myEnumerable.First()在执行两次时返回不同值的示例非常容易:
class A {
public A(string value) { Value = value; }
public string Value {get; set; }
}
static IEnumerable<A> getFixedIEnumerable() {
return new A[] { new A("Hello"), new A("World") };
}
static IEnumerable<A> getDynamicIEnumerable() {
yield return new A("Hello");
yield return new A("World");
}
static void Main(string[] args)
{
IEnumerable<A> fix = getFixedIEnumerable();
IEnumerable<A> dyn = getDynamicIEnumerable();
Console.WriteLine(fix.First() == fix.First()); // true
Console.WriteLine(dyn.First() == dyn.First()); // false
}
Run Code Online (Sandbox Code Playgroud)
这不仅仅是一个学术性的例子:使用流行from ... in ... select new …
我试图在使用非常大的字符串的.NET应用程序中调试内存问题.为此,我想设置一些断点并在执行的各个阶段分析堆.
问题是:当使用Visual Studio 2015的诊断工具时,似乎只有在没有调试的情况下启动应用程序时才会显示堆上的大字符串.这很不方便,因为它阻止我设置断点.
问题:这是一个已知的错误吗?或者我错误地使用诊断工具?
如何重现
使用以下代码创建新的C#控制台应用程序(.NET 4.6.1):
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
string test1 = new string('a', 100000000);
Thread.Sleep(2000);
string test2 = new string('a', 100000000);
Thread.Sleep(2000);
string test3 = new string('a', 100000000);
Console.WriteLine("Done");
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)激活诊断工具(Ctrl + Alt + F2)并使用调试启动应用程序(F5).观察内存使用情况并注意每个字符串分配会将内存使用量增加200MB.在内存使用量达到最大值后,获取内存快照并查看堆.
观察到堆上占用最多内存的对象类型是一个10 KB的图标.显然,这是不正确的.
停止申请.使用诊断工具再次启动它,但不进行调试(Alt + F2).选择"内存使用"并开始.
再次注意内存的增加,拍摄快照并查看它.
观察显示三个大字符串(应该是).
当我从集合中访问它们的属性时,我发现ValueTuples的评估方式不同.
public static List<Tuple<string, bool>> MyTupleList = new List<Tuple<string, bool>>
{
new Tuple<string, bool>("test", true)
};
public static List<(string b, bool c)> MyList = new List<(string b, bool c)>
{
("test", true)
};
Run Code Online (Sandbox Code Playgroud)
为什么这两个突出显示的行的评估方式不同,如何更改"MyList [0] .c"以正确获取值?
c# ×5
.net ×4
ado.net ×1
asp.net ×1
c#-7.3 ×1
coding-style ×1
debugging ×1
enums ×1
exception ×1
hang ×1
html ×1
ienumerable ×1
linq ×1
profiling ×1
reference ×1
sql-server ×1
valuetuple ×1
vb.net ×1
webforms ×1
wpf ×1