简体   繁体   中英

Is is possible to extend constructors in c#?

I am wondering if there is an existing class (such as UIColor from Monotouch) if there is a way to extend a constructor. That would make working with the library we have easier.

public static class UIColorExtender
{
    public UIColor(string hex)
    {
        this = ConvertHexToUIColor(hex); // This isn't necessarily the code, just filler.
    }
}

No, there is no such way presently in C#. Inherit from the class and use your own constructor logic. Use the new class in place of the old one.

Maybe this question is trying to achieve the same as you? UIColor from Hex in Monotouch

When looking at the UIColor class, it seems that it mostly uses a factory pattern when using other formats than just 4 float values for R, G, B and alpha:

UIColor.FromHSB(float, float, float)
UIColor.FromWhiteAlpha(float, float)

..and many more

So I think the best solution would be like Luis' in the question above.

Constructors can't be extended. You can inherit from the class and implement your own or, if the class in question isn't full of read-only properties, create an initialization method to call after the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM