I'm trying to create classes to encapsulate validation and logic for objects like Email , URL , phone number and so on . in the first try I found that I'm repeating the same code in all classes specially static IsValid
and the Constructor
. so I decided to create a base class to put all the same codes in it . so there is a base class that other classes inherit it . it's abstract as I don't want it to be used directly .
public abstract class BaseClass
{
protected string value;
private bool isValid;
public bool IsValid{get { return this.isValid;}}
protected virtual string RegexPattern{get;}
protected virtual RegexOptions RegexOption{get;}
private BaseClase(){}
protected BaseClass(string value)
{
this.isValid = Validator.IsValid(value , RegexPattern, RegexOption);
this.value = this.isValid ? value : string.Empty;
}
public static bool Validate(string value)
{
return Validator.IsValid(value ,RegexPattern, RegexOption); // rror
}
}
public class Email
{
private override string RegexPattern
{
get
{
return ".*";
}
}
private override RegexOptions RegexOption
{
get
{
return RegexOptions.SingleLine;
}
}
public string Address{get {return this.value; }}
public Email(string address) : base(address){}
}
the problem is with the static IsValid
method of BaseClass . in the current code it throws errors as RegexPattern
and RegexOption
are instance members . I don't want to defined the same value twice for instance and static methods . it works if I use
const string RegexPattern= ".*";
const RegexOptions RegexOption =RegexOptions.SingleLine;
but I need to be able to override these values in sub classes so this is not applicable . and as I have defined the BaseClass
as abstract
I cant instantiate it inside static method to have access to properties .
and as I want to use static method just like Email.IsValid("[email protected]");
, I don't know how to pass an instance through it .
so , how can I have access to RegexOption
and RegexPattern
in this static method ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…