Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

inheritance - C#: override a property of the parent class

I have a class that inherits from X509Certificate2. I want the NotAfter property to be in UTC rather than local time. I'm pretty new to C# and was wondering if what I have below is the best way of doing it?

internal class Certificate : X509Certificate2
{
    public new DateTime NotAfter 
    {
        get { return base.NotAfter.ToUniversalTime(); }
    }

EDIT When I changed it to this:

public override DateTime NotAfter 
{
    get { return base.NotAfter.ToUniversalTime(); }
}

Resharper complained that "There is not suitable property for override"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you have done there is member hiding. If the class you are deriving from has marked the property as virtual, or is overriding it from it's base (if it has one) you use the override keyword:

public override DateTime NotAfter

The member hiding can be used when the base class has marked it virtual, however if someone cast a reference of your class into the base class and accessed the member, they would bypass your new hiding. With true inheritance using override, this problem does not occur.

As has been noted by someone, this property is not marked virtual:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.notafter.aspx

Member hiding will allow you to get around this if people use your class directly, but the moment someone casts your class back to a base type, they get the base value:

class MyClass : Cert...

MyClass c = new MyClass();
DateTime foo = c.NotAfter; // Your newly specified property.

Cert cBase = (Cert)c;
foo = cBase.NotAfter; // Oops, base value.  Inheritance cures this, but only with virtual members.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...