C#用更具体的类型覆盖抽象属性 [英] C# Override abstract property with more specific type

查看:31
本文介绍了C#用更具体的类型覆盖抽象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当简单的问题,但我在任何地方都找不到合适的解决方案.我想在我的抽象父类中指定一个抽象对象 CustomValues 作为属性.但是,从它继承的类应该能够使用更具体的类型作为此属性 CustomValues 的对象.起初我以为我会通过一个接口来解决问题,但不幸的是,这也没有奏效.你怎么做这样的事情,它有效?

I have a rather simple problem, but I can't find a proper solution anywhere. I would like to specify an abstract object CustomValues as property in my abstract parent class. However, the class inheriting from it should be able to use a more specific type as an object for this property CustomValues. At first I thought I would solve the problem by an interface, but unfortunately that didn't work out either. How do you do something like that, that it works?

public abstract class MyAbstract {
    public abstract object CustomValues { get; set; }
}

public class MyImplementation : MyAbstract {
    public override MySpecificClass CustomValues { get; set; }
}

这会抛出三个错误:

  • 缺少 getter 实现
  • 缺少 setter 的实现
  • 类型 objectMySpecificClass 之间的类型不匹配
  • Missing implementation for getter
  • Missing implementation for setter
  • Type missmatch between type object and MySpecificClass

推荐答案

我认为您最初认为使用接口(+ 泛型)的想法是正确的.通常,您可能还想添加类型约束.

I think your original thought that use an interface (+ generic) was at the correct direction. In general you might want to add type constraints as well.

public interface ICustomValues {
  ....
}

public class MySpecificClass : ICustomValues {
  ....
}

public abstract class MyAbstract<T> where T : ICustomValues {
   public abstract T CustomValues {
     get;
     set;
   }
}


public class MyImplementation: MyAbstract<MySpecificClass>  {
  public override   MySpecificClass CustomValues { get; set; }
}

这篇关于C#用更具体的类型覆盖抽象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆