[英]C# Override abstract property with more specific type
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.我想在我的抽象父类中指定一个抽象对象 CustomValues 作为属性。 However, the class inheriting from it should be able to use a more specific type as an object for this property CustomValues.但是,从它继承的类应该能够使用更具体的类型作为此属性 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; }
}
This will throw me three errors:这会给我带来三个错误:
object
and MySpecificClass
类型object
和MySpecificClass
之间的类型不MySpecificClass
The solution suggested in the comments would look something like this.评论中建议的解决方案看起来像这样。 (I'm assuming CustomValues
should be a collection of something.) (我假设CustomValues
应该是一些东西的集合。)
public class MyClass<T>
{
public ICollection<T> CustomValues { get; set; }
}
Or to ensure CustomValues
itself cannot be reassigned, but can be accessed and added to:或者确保不能重新分配CustomValues
本身,但可以访问并添加到:
public class MyClass<T>
{
public ICollection<T> CustomValues { get; } = new List<T>();
}
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; }
}
Thanks to you all guys.谢谢大家。 I found the solution by using a generic properly :我通过正确使用泛型找到了解决方案:
public abstract class MyAbstract<T> {
public abstract T CustomValues { get; set; }
}
public class MyImplementation : MyAbstract<MySpecificClass> {
public override MySpecificClass CustomValues { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.