简体   繁体   English

C# 中的用例 Debug.Assert 是什么

[英]What is the usecase Debug.Assert in C#

Recently, I came across the Debug.Assert in C#.最近,我在 C# 中遇到了Debug.Assert However this has been into programming for years but this came across to me as new & quite puzzled me.然而,这已经进入编程多年,但这对我来说是新的,让我很困惑。

Lets say I have C# method where input field is mandatory like假设我有C#方法,其中输入字段是强制性的,例如

public class User
{
   public class GetUser(string email) // email is required field
   {
       if(!string.IsNullOrEmptySpace(email)
       {
            
          //ToDo
        
       }
   }


   public class GetUserByEmail(string email) // email is required field
   {
         Debug.Assert(email != null); 
         //Assert method takes a boolean value and throws an exception if the value is false

        // ToDo
        
   }
}

What is the difference between these 2 approaches or use-case of the second approach?这两种方法或第二种方法的用例有什么区别?

Should I continue using Debug.Assert lib in.Net Core?我应该继续在.Net Core 中使用 Debug.Assert lib 吗?

Thanks!谢谢!

Debug.Assert as you see throws an exception when it receives a false value.如您所见, Debug.Assert在收到 false 值时会引发异常。 We use this to validate developer assumptions.我们使用它来验证开发人员的假设。 For example: lets say you just coded a function that requires the passed in parameter to be positive.例如:假设您刚刚编写了一个要求传入参数为正的 function。 So you want to make sure that no developer on your team passes a negative value.因此,您要确保团队中没有开发人员传递负值。 So you would use Debug.Assert there.所以你会在那里使用Debug.Assert However, this line gets completely removed if you build RELEASE so do NOT use it for business logic.但是,如果您构建RELEASE ,此行将被完全删除,因此不要将其用于业务逻辑。 Its just a helper to ensure that you have not forgotten an assumption you made while writing some logic.它只是一个帮助,以确保您在编写一些逻辑时没有忘记您所做的假设。

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

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