Tag: 接口

为什么在类中实现的C#接口方法必须是公共的?

我有一个inheritance接口的类。 接口成员方法是在我的类中实现的,没有访问修饰符(因此,默认情况下它是私有的)。 我收到错误“无法实现接口成员,因为它不公开”。 为什么不允许这样做? 我不能覆盖辅助function吗?

如何强制inheritance类在C#中实现静态方法?

我想要做的就是确保类Item的子类实现静态方法,并且我希望在编译时检查它以避免运行时错误。 使用静态方法的抽象类似乎不起作用: 错误:无法将静态成员标记为覆盖,虚拟或抽象 public abstract class Item { public static abstract Item GetHistoricalItem(int id, DateTime pastDateTime); } public class Customer : Item { public static override Customer GetHistoricalItem(int id, DateTime pastDateTime) { return new Customer(); } } public class Address : Item { public static override Address GetHistoricalItem(int id, DateTime pastDateTime) { return new Address(); […]

如何编写在C#中实现给定接口的通用容器类?

上下文:.NET 3.5,VS2008。 我不确定这个问题的标题,所以也可以自由评论标题:-) 这是场景:我有几个类,比如Foo和Bar,它们都实现了以下接口: public interface IStartable { void Start(); void Stop(); } 现在我想要一个容器类,它在构造函数中获取一个IEnumerable 作为参数。 反过来,这个类也应该实现IStartable接口: public class StartableGroup : IStartable // this is the container class { private readonly IEnumerable startables; public StartableGroup(IEnumerable startables) { this.startables = startables; } public void Start() { foreach (var startable in startables) { startable.Start(); } } public void […]

接口成员的属性不起作用

在我的应用程序中,有几个模型需要Password属性(例如, Registration和ChangePassword模型)。 Password属性具有DataType和Required等属性。 因此,为了确保可重用性的一致性,我创建了: interface IPasswordContainer{ [Required(ErrorMessage = “Please specify your password”)] [DataType(DataType.Password)] string Password { get; set; } } 和 class RegistrationModel : IPasswordContainer { public string Password { get; set; } } 不幸的是,属性不起作用。 然后我尝试将界面更改为类: public class PasswordContainer { [Required(ErrorMessage = “Please specify your password”)] [DataType(DataType.Password)] public virtual string Password { get; set; } […]