我写了一些代码来测试try-catch的影响,但看到了一些令人惊讶的结果.
static void Main(string[] args)
{
Thread.CurrentThread.Priority = ThreadPriority.Highest;
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
long start = 0, stop = 0, elapsed = 0;
double avg = 0.0;
long temp = Fibo(1);
for (int i = 1; i < 100000000; i++)
{
start = Stopwatch.GetTimestamp();
temp = Fibo(100);
stop = Stopwatch.GetTimestamp();
elapsed = stop - start;
avg = avg + ((double)elapsed - avg) / i;
}
Console.WriteLine("Elapsed: " + avg);
Console.ReadKey();
}
static long Fibo(int n)
{
long n1 = 0, n2 …Run Code Online (Sandbox Code Playgroud) 在心理上,当C++编译将其转换为汇编程序时,我总是想知道try/throw/catch在幕后是怎么看的.但是因为我从来没有使用它,所以我从来没有去过它(有些人会说懒惰).
是用于跟踪trys 的普通堆栈,还是仅为此目的而保留的单独的每线程堆栈?MSVC和g ++之间的实现是大还是小?请告诉我一些伪asm(IA-32也可以)所以我永远不必自己查看!:)
编辑:现在我了解了基于IA-32处理的MSVC实现的基础知识.任何人都知道在IA-32或其他任何CPU上的g ++?
如果你认为有可能获得空指针异常,你应该使用if语句来确保变量不为null,还是应该捕获异常?
我没有看到任何区别,因为你可以把你的逻辑处理if语句或catch块中的空指针,那么哪一个是最好的做法?
我有一个从 UnityEngine.EventSystems 实现 IDragHandler 和 IDropHandler 的游戏对象。
在 OnDrop 中,我想检查一下,这个对象是否被放置在另一个对象的前面。我正在使用 Physics.Raycast,但它仅在某些情况下返回 true。我使用屏幕点到光线作为我的光线方向,并将此变换作为 Raycast 光线的原点。
我的代码:
public void OnDrop(PointerEventData eventData)
{
var screenRay = Camera.main.ScreenPointToRay(new Vector3(eventData.position.x, eventData.position.y, 0.0f));
var thisToObjectBehind = new Ray(transform.position, screenRay.direction);
Debug.DrawRay(thisToObjectBehind.origin, thisToObjectBehind.direction, Color.yellow, 20.0f, false);
RaycastHit hit;
if (Physics.Raycast(thisToObjectBehind, out hit))
{
Debug.LogFormat("Dropped in front of {0}!", hit.transform);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用透视相机。当对象直接从屏幕/相机放置在对象前面时,Physics.Raycast 有时会返回 true,但“hit”包含这个,而不是后面的对象。有时它返回false。这两个结果都不是预期的,这背后有一些物体应该可以用于 Raycast。
当对象被放置在摄像机视图外围的前面对象中时,Physics.Raycast 成功找到后面的对象。
Debug 射线看起来不错,它是从我放下的对象中绘制的,向后绘制到它应该击中的对象。
在ASP.NET中,我想了解您处理异常的最佳方法是什么.
非常感谢您的帮助谢谢!
如何在调用 return 之前/之后执行代码的某些部分。例如 return 可能在一个方法中被多次调用,因此我不希望在 return 之前复制粘贴相同的行。
我可能是错的,但有些人告诉我,try 块使代码运行缓慢,并且我的方法被调用了 1000 多次,因此即使可以使用 try/finally 块完成此任务,我也想避免它。
例子:
void method()
{
MyObject activator = new ...
AnotherObject something = new ...
SomethingElse asdf = new ...
// some other variables
if(..)
// Deactivate activator, close things, confirm user exited
// Do some post calculations
return;
if(..)
// Deactivate activator, close things, confirm user exited
// Do some post calculations
return;
if(..)
// Deactivate activator, close things, confirm user exited
// Do some post calculations …Run Code Online (Sandbox Code Playgroud) 我对 try catch 的了解有限。但我想知道它是否可以用来获得性能。
例如,我正在创建这个体素引擎,其中一个函数是这样的:
Block GetBlockInChunk(Vector Position){
if(InBound(Position)){
return Database.GetBlock();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
这里它必须检查给定位置的边界,使用try catch,然后你可以删除它们吗?
Block GetBlockInChunk(Vector Position){
try{
return Database.GetBlock();
}
catch{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
我觉得这可能是可怕的做法,但我很好奇。