Mark parameters as NOT nullable in C#/.NET?

后端 未结 6 2009
粉色の甜心
粉色の甜心 2020-12-02 21:53

Is there a simple attribute or data contract that I can assign to a function parameter that prevents null from being passed in C#/.NET? Ideally this would also

6条回答
  •  抹茶落季
    2020-12-02 22:21

    not the prettiest but:

    public static bool ContainsNullParameters(object[] methodParams)
    {
         return (from o in methodParams where o == null).Count() > 0;
    }
    

    you could get more creative in the ContainsNullParameters method too:

    public static bool ContainsNullParameters(Dictionary methodParams, out ArgumentNullException containsNullParameters)
           {
                var nullParams = from o in methodParams
                                 where o.Value == null
                                 select o;
    
                bool paramsNull = nullParams.Count() > 0;
    
    
                if (paramsNull)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (var param in nullParams)
                        sb.Append(param.Key + " is null. ");
    
                    containsNullParameters = new ArgumentNullException(sb.ToString());
                }
                else
                    containsNullParameters = null;
    
                return paramsNull;
            }
    

    of course you could use an interceptor or reflection but these are easy to follow/use with little overhead

提交回复
热议问题