检查属性值是否为空

编程入门 行业动态 更新时间:2024-10-10 10:32:53
本文介绍了检查属性值是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

亲爱的ALl, 如何根据数据类型检查属性值是否为空 如下 我有一般方法获取属性名称和此方法检查属性的验证,但现在我想检查如果值不为空类型可以(列出<>,对象,Stringbuilder,intger,datadictionary,任何东西)

Dear ALl, How Can i Check If Property Value Is Empty According To Data type As Below I have Made General Method takes Properties names And This Method Check Validation Of The Properties but now I want to check If Value Is Not empty Type Can Be (List<>,Object,Stringbuilder,intger, datadictionary, Any thing)

public void validRequiredProps<T>(List<string> lstRequiredProps) { bool bValid = true; foreach (var kvpList in lstRequiredProps) { PropertyInfo PropName = typeof(T).GetProperty(kvpList); Type typeCode = PropName.PropertyType; // t will be System.String var PropValue = PropName.GetValue(this, null); var properties = typeCode.GetProperties(BindingFlags.Public | BindingFlags.Instance); if (PropValue == null) { sbErrorDescription.Append("The Property :" + PropName + "Has null Value"); bValid = false; break; } else { // Check Data type And Empty Value?? } } }

或任何让它更通用的想法 谢谢

Or Any Idea To Make it More Generalize Thanks

推荐答案

首先你要定义什么'空'对于你想要处理的每种类型都意味着...... 例如整数是空的?什么是datetime为空? 之后你可以为每种类型写一个扩展方法来检查空(比如字符串的IsNullOrEmpty)...... msdn.microsoft/en-us//library/bb383977.aspx [ ^ ] First of all you have to define what 'empty' means for every type you want to handle... For instance what is empty for integer? What is empty for datetime? After that you may write an extension method for each type to check for empty (something like IsNullOrEmpty of string)... msdn.microsoft/en-us//library/bb383977.aspx[^]

作为 Kornfeld Eliyahu Peter [ ^ ]提到(见解决方案1),需要编写自定义扩展方法检查对象是否为空。请参阅: object.notempty [ ^ ]。您可能感兴趣的 object.isdefaultfortype [ ^ ]方法。 在任何其他情况下,你需要显式地将对象转换为字符串以检查 string.IsNullOrEmpty( ) [ ^ ] As Kornfeld Eliyahu Peter[^] mentioned (see solution 1), you need to write custom extension method to check if object is empty. See this: object.notempty[^]. You might be interested object.isdefaultfortype[^] method too. In any other case, you need to explicitly convert object to string to check if string.IsNullOrEmpty()[^] if(string.IsNullOrEmpty((string)PropValue)) { //object is empty }

您可以在此处找到更多详细信息:如何在C#.NET 3.5中检查对象是空还是空? [ ^ ]

更多推荐

检查属性值是否为空

本文发布于:2023-11-09 11:46:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572291.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!