开发者

how to do validations when composing object of a class in other class?

I have an IPAddress class which has one property named ip and in its setter I am validating data coming and if data is invalid it throws an error. (Its code is as the following):

private string ip;

public string IP
{
  get { return ip; }
  set { string PartsOfIP = value.Split('.');

  if (PartsOfIP.Length == 4)
  {
    foreach (string part in PartsOfIP)
     { int a = 0; bool result = int.TryParse(part, out a);

        if (result != true)
        {
          throw new Exception("Invalid IP");

        }
        else { ip = value; }
      }

  }
  else { throw new Exception("Invalid IP");
  }
}

In User Class I want to compose an o开发者_如何学Pythonbject of IPAddress class.

I am doing validations for properties of User in User class and validations of Ip in IPAddress class.

My question is how I will compose IPAddress object in UserClass and what will be syntax for this ?

If I again mention get and set here with IPAddress object in User class will my earlier mentioned (in IPAddress class) getter and setter work ?


  1. Create constructor for UserClass like this:

    public IPAddress userIpAddress;
    // Other fields and properties
    
    public UserCLass(IPAddress ipAddress, .... other fields)
    {
        userIpAddress = ipAddress; // here validation for IPAddress will be called
    }
    
  2. Use regular expressions for IPAddress validation


Wouldn't IPAddress.TryParse help here?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜