处理异常的最佳实践是什么,而无需在任何地方放置try/catch块?
我有创建一个致力于接收和处理异常的类的想法,但我想知道它是否是一个好的设计理念.这样的类会收到异常然后根据其类型或错误代码决定如何处理它,甚至可以解析堆栈跟踪以获取特定信息等.
以下是背后和实施的基本思想:
public class ExceptionHandler
{
public static void Handle(Exception e)
{
if (e.GetBaseException().GetType() == typeof(ArgumentException))
{
Console.WriteLine("You caught an ArgumentException.");
}
else
{
Console.WriteLine("You did not catch an exception.");
throw e; // re-throwing is the default behavior
}
}
}
public static class ExceptionThrower
{
public static void TriggerException(bool isTrigger)
{
if (isTrigger)
throw new ArgumentException("You threw an exception.");
else
Console.WriteLine("You did not throw an exception.");
}
}
class Program
{
static void Main(string[] args)
{
try
{ …Run Code Online (Sandbox Code Playgroud) 有一个Action委托并尝试在lambdas中使用其中的三元运算符:
Action<string> action = new Action<string>( str => (str == null) ?
Console.WriteLine("isnull") : Console.WriteLine("isnotnull")
Run Code Online (Sandbox Code Playgroud)
给出旧的"仅赋值,减量等允许"错误.
这有可能吗?
我有一个基于AJAX的WebGet方法返回JSON.它不适用于几千行的JSON结果(如果我只使用100行左右).我注意到浏览器只是暂停而没有任何反应,没有任何显示Firebug控制台的信息:
[WebGet]
public HttpTransactionTransformArgs Test()
{
HttpTransactionFilterArgs args = new HttpTransactionFilterArgs();
args.Context = "MyDb";
args.Entity = "MyDbRow";
args.Key = "1";
args.Option = null;
HttpTransactionTransformArgs targs = new HttpDataPush().TransformRequest(args);
return targs;
}
[DataContract]
[KnownType(typeof(HttpTransactionTransformArgs))]
[KnownType(typeof(HttpColumnDefinition))]
[KnownType(typeof(HttpDataRow))]
public class HttpTransactionTransformArgs
{
[DataMember]
public string EntityName { get; set; }
[DataMember]
public List<HttpColumnDefinition> Schema { get; set; }
[DataMember]
public List<HttpDataRow> Data { get; set; }
[DataMember]
public bool TransactionSuccessful { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是WCF的服务器端配置:
<service name="Test.AJAXService" behaviorConfiguration="metadataBehavior">
<endpoint address="" behaviorConfiguration="Test.AJAXServiceAspNetAjaxBehavior"
bindingConfiguration="webHttpConfig" …Run Code Online (Sandbox Code Playgroud) 我的页面上有一个表单,用户可以在其中发送电子邮件,
try
{
smtpClient.Send(message);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Key",
"alert('Thank you for your submission.');", true);
}
catch(Exception)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Key",
"alert('There was an error processing your request.');", true);
}
Response.Redirect("home.aspx");
Run Code Online (Sandbox Code Playgroud)
警报没有出现,页面只是立即重定向,除非我注释掉Response.Redirect,然后警报工作.我想显示警报然后重定向.
怎么能实现这一目标?我想过以某种方式使用计时器,但我不确定这是否是最佳解决方案.
谢谢.
我按照此链接的教程创建一个原始套接字数据包嗅探器:
http://www.security-freak.net/raw-sockets/sniffer_eth_ip.c
代码使用ntoa()函数来获取源/目标IP地址的点符号版本,但据我所知,该函数已被弃用,因此这些行导致了问题.
ip_header = (struct iphdr*)(packet + sizeof(struct ethhdr));
/* print the Source and Destination IP address */
printf("Dest IP address: %d\n", inet_ntoa(ip_header->daddr));
printf("Source IP address: %d\n", inet_ntoa(ip_header->saddr));
printf("TTL = %d\n", ip_header->ttl);
Run Code Online (Sandbox Code Playgroud)
在我的系统(Ubuntu 11.04)上,我只能在arpa/inet.h中找到inet_ntoa()函数,但教程甚至没有使用该头文件.当我包含arpa/inet.h时,我得到了这个编译错误:
sniffer.c:154:4: error: incompatible type for argument 1 of ‘inet_ntoa’
/usr/include/arpa/inet.h:54:14: note: expected ‘struct in_addr’ but argument is of type ‘__be32’
Run Code Online (Sandbox Code Playgroud)
所以我理解我需要使用struct in_addr,但我不熟悉这种类型'__be32'.有人可以帮忙吗?
编辑 - 实际上让这个工作做一些相当复杂的铸造,但有更好的方法吗?
printf("Dest IP address: %s\n", inet_ntoa(*(struct in_addr*)&ip_header->daddr));
printf("Source IP address: %s\n", inet_ntoa(*(struct in_addr*)&ip_header->saddr));
Run Code Online (Sandbox Code Playgroud) 我想在一个任务内部的间隔上运行一个函数.就像是,
Task t = Task.Factory.StartNew(() => {
while (notCanceled()) {
doSomething();
Thread.Sleep(interval);
}
});
Run Code Online (Sandbox Code Playgroud)
在这里使用Thread.Sleep()是一个坏主意吗?任务是长时间运行的,睡眠时间也可能很长(几分钟,甚至几小时).
一种替代方法是使用System.Timers.Timer或System.Threading.Timer.但是这两个都会导致产生额外的线程(Elapsed事件发生在新的线程池线程上).因此,对于每个重复任务,将有2个线程而不是1.任务已经是异步的,所以我不希望以这种方式使事情复杂化.
另一种行为相似的方式是使用ManualResetEvent,
ManualResetEvent m = new ManualResetEvent(false);
void sleep(int milliseconds)
{
m.WaitOne(milliseconds);
}
Run Code Online (Sandbox Code Playgroud)
由于永远不会调用m.Set(),因此它总是等待适当的时间,也是单线程的.这是否比Thread.Sleep()有任何明显的优势?
想知道这里最好的做法是什么.
思考?
我怎样才能修改下面的xsl,以便在for-each循环中放置图像,每个表行放置2个图像,而不是4个(它当前的作用).
我相信它与mod功能有关吗?
我尝试将foreach兄弟循环拆分到另一行,但只有第一个图像显示在第一行,其余图像显示在第二行.
<xsl:for-each select="Finding">
<xsl:if test="FindingType = 'A'">
<xsl:variable name="nImage" select="count(Image)" />
<tr><td class="di"><table width="100%" class="findings">
<tr><td class="shade" colspan="4"><p class="g"><b>Finding</b></p></td></tr>
<xsl:for-each select="Image[position() mod 4 = 1]">
<tr><td width="25%" align="left" valign="top"><p class="g"><img src="{.}" height="128" width="128" hspace="12"/><br />
<xsl:value-of select="@Type" /><xsl:text> </xsl:text> <xsl:value-of select="@SubType" />
<xsl:if test="@Position != ''"> (<xsl:value-of select="@Position" />) </xsl:if><br /><br />
</p>
</td></tr>
<tr><xsl:for-each select=". | following-sibling::Image[position() < 4 and (position() mod 4 = 0 or position() mod 4 = 1 or position() mod 4 = 2)]"> …Run Code Online (Sandbox Code Playgroud) 我正在尝试解析IL,以发出一种方法。我已经在string []中获得了方法的IL代码,其中每个字符串都是IL指令。我遍历此数组并使用ILGenerator添加OpCodes:
foreach (string ins in instructions) //string representations of IL
{
string opCode = ins.Split(':').ElementAt(1);
// other conditions omitted
if (opCode.Contains("br.s"))
{
Label targetInstruction = ilGenerator.DefineLabel();
ilGenerator.MarkLabel(targetInstruction);
ilGenerator.Emit(OpCodes.Br_S, targetInstruction);
}
Run Code Online (Sandbox Code Playgroud)
这是我需要重现的IL:
Source IL:
IL_0000: nop
IL_0001: ldstr "Hello, World!"
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
Target IL:
IL_0000: nop
IL_0001: ldstr "Hello, World!"
IL_0006: stloc.0
IL_0007: br.s IL_0007 // this is wrong -- needs to point to IL_0009
IL_0009: ldloc.0
IL_000a: ret
Run Code Online (Sandbox Code Playgroud)
如您所见,br.s调用指向自身,这当然会导致无限循环。如何获得源代码中的以下说明?这与使用Reflection.Emit.Label有关,但是我不确定它是如何工作的。
编辑通过上面看到的IL就是这种简单方法, …
代理对象并使用城堡动态代理拦截方法时,是否可以获取目标方法的返回值?我尝试过使用以下方法,
object result = invocation.GetConcreteMethod().Invoke(instance, null);
object result = invocation.GetConcreteMethodInvocationTarget().Invoke(instance, null);
Run Code Online (Sandbox Code Playgroud)
这会导致无限循环.我希望能够在调用Invocation.Proceed()之前获取原始目标方法的返回值.
编辑 - Fyi我通过使用Activator.CreateInstance让它工作,但我想知道是否有更简洁的方法来实现等效:
object instance = Activator.CreateInstance(invocation.TargetType);
invocation.MethodInvocationTarget.Invoke(instance, invocation.Arguments);
Run Code Online (Sandbox Code Playgroud)
问题是这只是原始对象的一个新的非代理实例,而我想要原始的非代理实例本身.
这是一个一般性的设计问题.我们经常使用接口来解耦组件,写入接口而不是实现等.有时使用基本注入技术的接口,例如,
interface IMyInterface
{
void DoSomething();
}
static class IMyInterfaceFactory
{
public static IMyInterface GetInstance()
{
return new MyInterfaceInstance();
}
}
class IMyInterfaceConsumer
{
IMyInterface mInterface;
public IMyInterfaceConsumer()
{
this.mInterface = IMyInterfaceFactory.GetInstance();
}
public void UseTheInterface()
{
this.mInterface.DoSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是关于使用var关键字.甚至没有使用真正的C#界面,但仍然在设计意义上创建一个"界面",
static class IMyInterfaceFactory
{
// of course, this doesnt need to be a single instance
static MyInterfaceInstance mSingleInstance;
// no longer programming to the interface, just returning the instance
public static MyInterfaceInstance GetInstance()
{
// null coalesce
return mSingleInstance …Run Code Online (Sandbox Code Playgroud)