2010-10-04 88 views
2

我想写我的第一个WCF服务。现在我只想获取一些对象的属性并将它们写入SQL Server。 并不是所有的属性值都会被设置,所以我想要在服务端接收对象,遍历对象的所有属性,并且如果有任何未设置的字符串数据类型,请将该值设置为“ ?”。 对象的所有属性都被定义为字符串类型如何设置属性的值,如果它为空?

我试着在这里找到下面的代码,但得到错误“对象与目标类型不匹配”。在下面指出的线上

 foreach (PropertyInfo pInfo in typeof(item).GetProperties()) 
     { 
      if (pInfo.PropertyType == typeof(String)) 
      { 
       if (pInfo.GetValue(this, null) == "") 
       //The above line results in "Object does not match target type." 
       { 
        pInfo.SetValue(this, "?", null); 
       } 
      } 
     } 

我该如何检查一个对象的字符串类型的属性是否没有设置?

回答

2

PropertyInfo.GetValue返回的值是object。不过,既然你知道该值是一个string你可以告诉编译器(因为你在上面的行选中)“我知道这是一个字符串”做铸造:

if (pInfo.PropertyType == typeof(String)) 
{ 
    string value = (string) pInfo.GetValue(this, null); 
    if (value == "") 
    { 

另外,我想补充一个额外null检查那里,以防万一值为空空。幸运的是,这里有string.IsNullOrEmpty方法:

if (pInfo.PropertyType == typeof(String)) 
{ 
    string value = (string) pInfo.GetValue(this, null); 
    if (string.IsNullOrEmpty(value)) 
    {