Processing parameters before calling the base constructor

孤街浪徒 提交于 2020-01-14 12:56:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!