代码之家  ›  专栏  ›  技术社区  ›  etoisarobot

如果属性为空,如何设置其值?

  •  2
  • etoisarobot  · 技术社区  · 14 年前

    我正在尝试编写我的第一个WCF服务。现在,我只想获取一个对象的一些属性,并将它们写入SQL Server。 并非所有属性值都将始终设置,因此我希望在服务端接收对象,循环访问对象上的所有属性,如果有任何未设置的字符串数据类型,请将该值设置为“?”。. 对象的所有属性都定义为字符串类型

    我正在尝试在此处找到以下代码,但在下面指示的行中得到错误“object does not match target type.”。

            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);
                    }
                } 
            }
    

    我应该如何检查对象上字符串类型的属性是否尚未设置?

    1 回复  |  直到 14 年前
        1
  •  2
  •   Dean Harding    14 年前

    返回的值 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))
        {