busObject.GetType().GetProperty("MyProperty").GetValue ...如何判断一个对象是否存在一个指定的属性如"MyProperty",如果不事先判断的话,上面的语句将会出错

解决方案 »

  1.   

           PropertyInfo pi = typeof(IDuxObjectItem).GetProperty(propName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
            if (pi == null)
            {
              throw new Exception("不存在名为" + propName + "的属性");
            }
      

  2.   


    你的就改成这个样:PropertyInfo pi = busObject.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
      if (pi == null)
      {
      throw new Exception("不存在名为" + propName + "的属性");
      }
      

  3.   

    busObject.GetType().GetProperty("MyProperty")判断它是否为null
      

  4.   

    还是简单封装一下吧,C# 示例L@_@K
    using System;namespace Scratch
    {
        class Program
        {
            static void Main(string[] args)
            {
                string propName = "IWanted";
                
                if (!TypeExistsProperty(typeof(string), propName))
                {
                    Console.Write("Are you crazy?");
                }
                Console.Read();
            }        public static bool TypeExistsProperty(Type givenType, string propertyName)
            {
                if (givenType == null || propertyName== null) 
                    return false;            return ((givenType.GetProperty(propertyName)) != null);
            }
        }
    }
      

  5.   

    Type T= GetType();
    if (T!= null)
    {
        PropertyInfo[] PropertyInfos = T.GetProperties();
        foreach (PropertyInfo P in PropertyInfos)
            textBox1.AppendText((P!=null?P.Name:"") + "\r\n");
    }