简体   繁体   中英

How do I do operations on an inherited base constructor in C#?

Example

public class ClassA
{
    public ClassA(string someString){}
}

public class ClassB : ClassA
{
    public ClassB(string someString):base(someString.ToLower()){}
}

I call the inherited ClassB constructor. I pass in a null. ToLower() throws an exception on a null. I want to check for a null before that happens. How can I do this?

Simple. Using null-coalescing operator :

public ClassB(string someString) : 
    base((someString ?? "").ToLower())
{
}

Or using ternary operator

public ClassB(string someString) : 
    base(someString == null ? "" : someString.ToLower())
{
}

Better yet, I'd suggest you to add a no-arg constuctor to ClassB , which will call base(string.Empty) .

尝试这个:

base(someString == null ? string.Empty : someString.ToLower())

Try this

public class ClassA
{
    public ClassA(string someString) { }
}

public class ClassB : ClassA
{
    public ClassB(string someString) : base(someString == null  ? "" :  someString.ToLower()) { }
}

You have already gotten answers on your question, but I just want to add that the approach strikes me as a bit odd. Is it really the caller's responsibility to make sure that the input is in lower case? I would definitely make this check and conversion in the base class constructor instead:

class Base
{
    private string _someString;
    public Base(string someString)
    {
        _someString = someString != null ? someString.ToLower() : null;
    }
}

class Derived : Base
{
    public Derived(string someString) : base(someString) { }
}

This way the base class is not dependent on how the derived class chooses to pass the argument.

You should check if someString is null in your base class and act accordingly, otherwise you can do something like this, but I think its very unreadable.

public class ClassB : ClassA
{
    public ClassB(string someString):base((String.IsNullOrEmpty(someString)) ? String.Empty : someString.ToLower()){}
}

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