显式成员实施的当前指导原则建议:
使用显式成员来近似私有接口实现.如果您只是出于基础架构原因需要实现接口,并且您从不希望开发人员直接从该类型调用该接口上的方法,那么明确地实现成员以从公共视图中"隐藏"它们.
公开一种替代方法来访问允许子类重写的任何显式实现的成员.
一个很好的例子就是你想要实现IXmlSerializable接口.该的ReadXml和中WriteXML有望方法由XmlSerializer的调用,而不是通常由开发商直接调用.
当提供一种替代方法来明确访问您希望允许被覆盖的成员时,调用显式实现的成员似乎是有意义的,以避免代码重复.考虑以下:
using System; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace Demo { ////// Demonstrates explicit implementation of the IXmlSerializable interface. /// [Serializable(), XmlRoot(ElementName = "foo")] public class Foo : IXmlSerializable { //============================================================ // IXmlSerializable Implementation //============================================================ #region GetSchema() ////// Returns an ///that describes the XML representation of the object. /// /// An ///that describes the XML representation of the object that is /// produced by the method and consumed by the method. /// This method is reserved and should not be used. XmlSchema IXmlSerializable.GetSchema() { return null; } #endregion #region ReadXml(XmlReader reader) ////// Generates an object from its XML representation. /// /// Thestream from which the object is deserialized. /// The void IXmlSerializable.ReadXml(XmlReader reader) { // Class state values read from supplied XmlReader } #endregion #region WriteXml(XmlWriter writer) ///is a null reference (Nothing in Visual Basic). /// Converts an object into its XML representation. /// /// Thestream to which the object is serialized. /// The void IXmlSerializable.WriteXml(XmlWriter writer) { // Current class state values written using supplied XmlWriter } #endregion //============================================================ // Public Methods //============================================================ #region WriteTo(XmlWriter writer) ///is a null reference (Nothing in Visual Basic). /// Saves the current /// Theto the specified . /// stream to which the is serialized. /// The public void WriteTo(XmlWriter writer) { writer.WriteStartElement("foo"); ((IXmlSerializable)this).WriteXml(writer); writer.WriteEndElement(); } #endregion } }is a null reference (Nothing in Visual Basic).
我的问题是关于WriteXml方法在此实现中的装箱有多昂贵.是((IXmlSerializable)这个.).WriteXml(作家)会显着阻碍性能?
在你的例子中没有拳击......它只是一个演员,它在编译时可以解析,因此它根本不会对性能产生任何影响.
编辑:使用ILDASM查看它,接口强制转换将为您提供虚拟方法调用与常规方法调用,但这可以忽略不计(仍然没有涉及到拳击).
编辑2:如果您使用结构而不是类,那么您将获得一个通过界面的框,更多的性能损失.