为什么C#这样设计?
据我所知,接口只描述行为,并且用于描述实现某些行为的接口的类的合同义务.
如果类希望在共享方法中实现该行为,为什么不应该这样做呢?
这是我想到的一个例子:
// These items will be displayed in a list on the screen.
public interface IListItem {
string ScreenName();
...
}
public class Animal: IListItem {
// All animals will be called "Animal".
public static string ScreenName() {
return "Animal";
}
....
}
public class Person: IListItem {
private string name;
// All persons will be called by their individual names.
public string ScreenName() {
return name;
}
....
}
Run Code Online (Sandbox Code Playgroud) 我有一个C#应用程序,它从一个有点不稳定的环境中托管的SQL Server中获取数据.我无法解决环境问题,所以我需要尽可能优雅地处理它们.
为此,我想重新尝试基础设施故障导致的操作,例如网络故障,SQL服务器脱机,因为它们正在重新启动,查询超时等.同时,我不想要如果逻辑错误失败,则重试查询.我只是希望那些将异常冒泡到客户端.
我的问题是:区分环境问题(丢失连接,超时)和其他类型的异常(即使环境稳定会发生逻辑错误之类的事情)的最佳方法是什么.
C#中有一个常用的模式来处理这样的事情吗?例如,是否有一个属性我可以在SqlConnection对象上检查以检测失败的连接?如果没有,解决这个问题的最佳方法是什么?
对于它的价值,我的代码并不特别:
using (SqlConnection connection = new SqlConnection(myConnectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = mySelectCommand;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Do something with the returned data.
}
}
}
Run Code Online (Sandbox Code Playgroud) 在C#中,可以通过几种不同的方式连接字符串:
使用串联运算符:
var newString = "The answer is '" + value + "'.";
Run Code Online (Sandbox Code Playgroud)
使用String.Format
:
var newString = String.Format("The answer is '{0}'.", value);
Run Code Online (Sandbox Code Playgroud)
使用String.Concat
:
var newString = String.Concat("The answer is '", value, "'.");
Run Code Online (Sandbox Code Playgroud)
每种方法的优点/缺点是什么?我应该什么时候比其他人更喜欢?
问题出现是因为开发人员之间的争论.一个从未使用String.Format
的级联-他认为,这是格式化字符串,而不是进行连结,那就是始终不可读,因为该字符串中的项目以错误的顺序表示.其他经常使用String.Format
的级联,因为他认为这使代码更易于阅读,特别是在有几套参与报价.这两个开发人员也使用连接运算符和String.Builder.
在对大型游戏程序进行概要分析后,我发现库函数rand()占用了总处理时间的很大一部分.我对随机数发生器的要求不是很繁重 - 通过大量纯随机性统计测试并不重要.我只想要一些便宜又快乐的东西.有什么建议?
在开发过程中,我通常使用Web Development Server(有时称为Cassini)测试ASP.Net应用程序.有时,当我发布到真正的IIS环境时,我注意到应用程序的行为有所不同.
那么,生产IIS服务器和ASP.Net Web开发服务器的行为方式有何不同?我并不是说功能集的差异(显然IIS有许多WDS中没有的功能),但它们处理ASP.Net的方式不同.
顺便说一句:对这个问题的回答中提到了一些差异,但我确信必须有更多.