问题
is it possible to process parameters before passing them into a base constructor?
As in:
A --> B
Where A is an abstract class and B is the child class.
A's constructor is like so:
Protected A (MyObject myObject)
B's constructor is like so:
Public B (string objectName)
I want it to be something like this
Public B (String objectName) : base (MyObject myObject)
{
myObject = new MyObject (objectName);
}
回答1:
If you want to do something non-trivial (that doesn't fit naturally into a single expression that you can inline into the base call), then the only way to do that is in a static method, for example:
public B (string objectName) : base (SomethingComplex(objectName))
{
//...
}
static MyObject SomethingComplex(string objectName)
{
// this can now be arbitrarily complex
if(string.IsNullOrWhiteSpace(objectName))
throw new ArgumentException("objectName")
// etc
return new MyObject(objectName);
}
回答2:
Yes, but only as a single expression:
public B(String objectName) : base(new MyObject(objectName)) {
}
Note that since this runs before the class is constructed, it cannot access instance members.
If you want to run more than a single expression (eg, parameter validation), you can call a static method.
来源:https://stackoverflow.com/questions/15027423/processing-parameters-before-calling-the-base-constructor