zoukankan      html  css  js  c++  java
  • 补充一个技术文章吧,否则真的对不起博客园

            /// <summary> 较安全的返回指定属性的值 </summary>
            
    /// <remarks>
            
    /// 例如,如果你想获得Company的CompanyCode的DefaultCode属性,可以使用
            
    /// <code>
            
    /// object code = _company.SafeGetValue("CompanyCode.DefaultCode");
            
    /// </code>
            
    /// 但注意:
            
    ///        传入的参数(属性名)不允许书写错误,在此方法中不对此进行检查;
            
    /// </remarks>

            public object SafeGetValue(string propertyName)
            
    {
                
    string[] props = propertyName.Split('.');
                
    string propName;
                PropertyInfo propInfo;
                
    object obj = this;
                Type objType;

                
    for (int i = 0; i < props.Length; i++)
                
    {
                    objType 
    = obj.GetType();

                    propName 
    = props[i];
                    
    if (propName.Trim().Length == 0)
                        
    throw new ArgumentException("propertyName");

                    
    try
                    
    {
                        propInfo 
    = objType.GetProperty(propName);
                        
    if (propInfo == null)
                            
    throw new ArgumentException("propertyName");

                        obj 
    = propInfo.GetValue(obj, null);
                    }

                    
    catch (AmbiguousMatchException)
                    
    {
                        PropertyDescriptorCollection propDescs 
    = TypeDescriptor.GetProperties(objType);
                        PropertyDescriptor propDesc 
    = propDescs.Find(propName, false);
                        
    if (propDesc == null)
                            
    throw new ArgumentException("propertyName");
                        
    else
                        
    {
                            obj 
    = propDesc.GetValue(obj);
                        }

                    }


                    
    if (obj == null)
                        
    return null;
                }

                
    return obj;
            }
  • 相关阅读:
    [LeetCode] 139. Word Break 单词拆分
    [LeetCode] 140. Word Break II 单词拆分II
    [LeetCode] 297. Serialize and Deserialize Binary Tree 二叉树的序列化和反序列化
    [LeetCode] 206. Reverse Linked List 反向链表
    [LeetCode] 92. Reverse Linked List II 反向链表II
    [LeetCode] 258. Add Digits 加数字
    [LeetCode] 66. Plus One 加一
    [LeetCode] 21. Merge Two Sorted Lists 合并有序链表
    [LeetCode] 88. Merge Sorted Array 合并有序数组
    [LeetCode] 10. Regular Expression Matching 正则表达式匹配
  • 原文地址:https://www.cnblogs.com/tansm/p/83582.html
Copyright © 2011-2022 走看看