类的属性验证null和字符串长度

时间:2015-05-24 02:35:53

标签: asp.net function c#-4.0 properties

我要将类属性传递给函数,但需要检查NULL和特定长度。我试图从UserInfo类中调用函数CheckProperty,但给出错误::

  1. “非静态字段,方法或属性UserInfo.CheckProperty(string,int)”
  2. 需要对象引用
  3. “字段初始化程序无法引用非静态字段,方法或属性UserInfo.UserAddr.get”
  4. public class clsUserBookKeeping     {

        public class UserInfo
        {
            public string UserId { get; set; }   
            public string UserName { get; set; } // length should not exceed 20 characters, if NULL pass "TBD"
            public string UserAddr { get; set; } // length should not exceed 120 characters, if NULL pass "TBD"
            public string UserContact { get; set; } // length should not exceed 20 characters, if NULL pass "TBD"
        }
    
        var output = getRecord (UserInfo.UserId, UserInfo.UserName, UserInfo.UserAddr, UserInfo.UserContact);
    
        private string CheckProperty(this string value, int maxLength)
        {
            if (string.IsNullOrEmpty(value))
            {
                return "TBD";
            }
            if (!string.IsNullOrEmpty(value) && value.Length > maxLength)
            {
                return value.Substring(0, maxLength);
            }
            return value;
        }
    }
    

    注意:公共类clsUserBookKeeping是类,它不在代码块中。

    我试过这个::

    public class UserInfo
    {
    
        public string UserId { get; set; }   
        public string UserName { get; set; } // length should not exceed 20, if NULL pass "TBD"
        public string UserAddr { get; set; } // length should not exceed 120, if NULL pass "TBD"
        public string UserContact { get; set; } // length should not exceed 20, if NULL pass "TBD"
    
        string getAddress = CheckProperty(UserAddr,120);
     }
    

    但是得到了错误。如何调用 CheckProperty 函数并将属性值传递给getRecord?

0 个答案:

没有答案
相关问题