问题描述
我有一个继承自X509Certificate2的类.我希望NotAfter属性位于UTC而不是本地时间.我是C#的新手,我想知道下面的内容是最好的方法吗?
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(); }
}
编辑当我将其更改为:
public override DateTime NotAfter
{
get { return base.NotAfter.ToUniversalTime(); }
}
Resharper抱怨没有合适的属性可以覆盖"
Resharper complained that "There is not suitable property for override"
推荐答案
您在那里所做的是成员隐藏.如果您派生的类已将该属性标记为virtual
,或从其基础(如果有)覆盖它,则可以使用override
关键字:
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
在基类已标记为virtual
时可以使用成员隐藏,但是,如果有人将对您的类的引用转换为基类并访问该成员,他们将绕过您的new
隐藏.使用override
进行真正的继承时,不会发生此问题.
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.
正如某人所指出的,此属性未标记为virtual
:
As has been noted by someone, this property is not marked virtual
:
如果人们直接使用您的类,则隐藏成员可以使您解决此问题,但是当有人将您的类强制转换为基本类型时,他们将获得基本值:
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.
这篇关于C#:覆盖父类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!