简体   繁体   English

C#:Debug.Assert() 条件复杂

[英]C#: Debug.Assert() with complex condition

I'm writing a library where internally it uses a ConcurrentQueue .我正在编写一个在内部使用ConcurrentQueue的库。 In one of the private method, I want to make sure that the item that I currently have is the item that will be dequeued (ie if I did not write my codes wrongly, this should be the expected behavior).在其中一种private方法中,我想确保我当前拥有的项目是将出队的项目(即,如果我没有错误地编写代码,这应该是预期的行为)。 How do I assert this correctly?我该如何正确断言?

My current attempt is:我目前的尝试是:

#if DEBUG
    object peeked = null;
    queue.TryPeek(out peeked);
    Debug.Assert(peeked == itemThatWillBeDequeued);
#endif

Which looks rather weird to me - if I need to use #if directive, then I wouldn't have used Debug.Assert() .这对我来说看起来很奇怪 - 如果我需要使用#if指令,那么我就不会使用Debug.Assert() However, there is no way I could directly place that ConcurrentQueue.TryPeek() into the assert statement inlinely either.但是,我也无法直接将ConcurrentQueue.TryPeek()直接放入 assert 语句中。 Furthermore, doing that inline would probably mean that ConcurrentQueue.TryPeek() would run in release at runtime (unless I'm mistaken).此外,内联可能意味着ConcurrentQueue.TryPeek()将在运行时以发行版运行(除非我弄错了)。

What should be the correct way to do this?正确的方法应该是什么?

If you want to avoid the extra method suggested by Bacon, you could use a LINQ expression:如果你想避免培根建议的额外方法,你可以使用 LINQ 表达式:

Debug.Assert(((Func<object>)(() => {
    object peeked;
    return queue.TryPeek(out peeked) ? peeked : null;
}))() == itemThatWillBeDequeued);

Explanation: ((Func<object>)(() => {... })) will create a function object from the enclosed code.说明: ((Func<object>)(() => {... }))将从随附的代码中创建一个 function object。 The () will execute this function and return its result. ()将执行此 function 并返回其结果。

you can wrap the call in a method您可以将调用包装在一个方法中

Debug.Assert(itemThatWillBeDequeued.equals(PeekQueue(queue)));

... ...

static object PeekQueue(ConcurrentQueue queue)
{
  object peeked = null;
  queue.TryPeek(out peeked);
  return peeked;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM