Tag: explicit interface

使用显式接口防止意外修改C#中的属性

我偶然发现了一个我以前没有注意到的C#方法解决方案的function。 也就是说,当我明确地实现支持setter的接口,并且隐式接口仅提供受保护的集合时,编译器在我调用它时明智地遵循受保护的集合。 因此,我获得了自动实现属性的大部分便利,但我可以防止不应该更改它们的客户端意外修改字段。 举个例子, virtual public DateTime CreatedOn { get; protected set; } virtual public DateTime? ModifiedOn { get; protected set; } #region IHaveUpdateDateFields Members DateTime IHaveUpdateDateFields.CreatedOn { get { return this.CreatedOn; } set { this.CreatedOn = value; } } DateTime? IHaveUpdateDateFields.ModifiedOn { get { return this.ModifiedOn; } set { this.ModifiedOn = value; } } […]

显式实现IDisposable

虽然在SO上有很多关于IDisposable的问答,但我还没有找到答案: 我通常遵循这样的做法:当我的一个类拥有一个IDisposable对象时,它也实现了IDisposable并在拥有的对象上调用Dispose 。 但是最近我遇到了一个明确实现IDisposable的类,因此阻止我直接调用Dispose强制我强制转换它,我觉得这很烦人且没必要。 所以问题是:为什么以及何时想要使用IDisposable的显式接口实现? 我知道明确实现接口有完美的正当理由,但就IDisposable ,原因并不十分清楚。

显式接口实现不能是虚拟的

为了记录,我已经看过这个连接项,但我真的不明白支持这个问题会是什么。 说我有以下代码: public interface IInterface { void Method(); } public class Base : IInterface { virtual void IInterface.Method() { throw new NotImplementedException(); } } 虚拟标识符有什么问题? 拥有虚拟修饰符可以override指示基类中有不同的实现。 我现在可以通过删除虚方法并创建如下的派生类来使其工作: public class Derived : IInterface { void IInterface.Method() { throw new NotImplementedException(); } } 但是这样我真的没有迹象表明我压倒了什么。 更新: 根据C#(部分:20.4.1显式接口成员实现)规范,有两个原因。 隐藏某些方法(我正在使用它)。 具有相同签名但具有不同返回类型的2个函数(例如,对IClonable有用)。 它没有说明为什么你不能使这些方法虚拟。 UPDATE2: 鉴于答案,我认为我应该在这里重新提出真正的问题。 如果以上两个原因是首先使接口的显式实现成为可能的原因。 如果将方法设为虚拟,为什么会出现问题?

类型参数“T”与外部类型“…”中的类型参数同名

public abstract class EntityBase { … } public interface IFoobar { void Foo(int x) where T : EntityBase, new(); } public interface IFoobar where T : EntityBase, new() { void Foo(int x); } public class Foobar : IFoobar, IFoobar where T : EntityBase, new() { public void Foo(int x) { … } void IFoobar.Foo(int x) […]

如何使用reflection来获取显式实现接口的属性?

更具体地说,如果我有: public class TempClass : TempInterface { int TempInterface.TempProperty { get; set; } int TempInterface.TempProperty2 { get; set; } public int TempProperty { get; set; } } public interface TempInterface { int TempProperty { get; set; } int TempProperty2 { get; set; } } 如何使用reflection来获取显式实现TempInterface的属性的所有propertyInfos? 谢谢。

C#中接口成员的访问修饰符

我从以下属性收到编译错误。 错误是: “修饰符’public’对此项无效” public System.Collections.Specialized.StringDictionary IWorkItemControl.Properties { get { return properties; } set { properties = value; } } 但如果我删除IWorkItemControl它编译得很好。 为什么我会收到此错误,签名中是否有/没有接口名称有什么区别?

为什么VS Metadata视图不显示显式接口实现的成员

前几天我正在查看C#布尔结构元数据。 Boolean实现了IConvertible接口。 但是看看布尔的成员,我看不到大多数IConvertible成员。 我和一些同事做了一些测试,包括创建我们自己的类,并得出结论,IConvertible必须明确地为Boolean实现。 问题是,为什么它们不可见? 我知道它可能是一个“按设计决定”但我明白如果检查元数据的任何人都可以看到它会增加更多的价值。 测试在VS2010 .NET4.0中完成

为什么一个类显式实现IDisposable而不是隐式?

我使用的是FtpWebResponse类,但没有看到Dispose方法。 事实certificate ,该类实现了IDisposable,但是明确地这样做,因此在调用Dispose之前必须先将实例强​​制转换为IDisposable: // response is an instance of FtpWebResposne ((IDisposable) response).Dispose(); 为什么像这样的类的设计者会选择明确地实现IDisposable? 正如Anthony Pegram所说 ,以这种方式做事掩盖了这样一个事实,即对象应该为每次使用课程时都没有查阅文档的普通开发人员处理。