[英]Interface needed to access overridden abstract property in classes derived from generic abstract base?
So my dilemma is that in order to access IntThing
's or StringThing
's MyProperty
from UtilityThing<T>
, I'm defining an interface with MyProperty
and using it as the generic constraint on T
in UtilityThing<T>
. 所以我的困境是,为了从
IntThing
UtilityThing<T>
访问IntThing
或StringThing
的MyProperty
,我定义了MyProperty
接口,并将其用作UtilityThing<T>
对T
的一般约束。 This is working, but seems redundant given that the same property is already defined in the abstract base. 这是可行的,但是鉴于抽象库中已经定义了相同的属性,因此似乎是多余的。 Am I missing a facet of design here, or is this actually the way it needs to be done in this instance?
我是否在这里缺少设计方面,或者这实际上是在这种情况下需要采用的方式?
public interface IThing {
string MyProperty { get; set; }
}
public abstract class Thing<T> {
protected string _MyProperty;
public abstract string MyProperty { get; set; }
public T OtherProperty { get; set; }
public string CommonMethod() {
return MyProperty + "foobar";
}
}
public class IntThing : Thing<int?>, IThing {
public override string MyProperty {
get { return _MyProperty; }
set { _MyProperty = value + OtherProperty.ToString(); }
}
}
public class StringThing: Thing<string>, IThing {
public override string MyProperty {
get { return _MyProperty; }
set { _MyProperty = OtherProperty + value; }
}
}
public class UtilityThing<T> where T: IThing, new() {
public T DoIt(SomeContext someContext, string name) {
string contextVal = someContext.GetValue(name);
var thing = new T { MyProperty = contextVal }
return thing;
}
}
You'll need to introduce a new generic type. 您需要引入一个新的泛型类型。 Once the new type is introduced you can eliminate the need of the interface.
引入新类型后,您就可以消除对接口的需求。
public class UtilityThing<T, I> where T : Thing<I>, new()
{
public T DoIt(SomeContext someContext, string name)
{
string contextVal = someContext.GetValue(name);
var thing = new T { MyProperty = contextVal };
return thing;
}
}
And you can use it like this: 您可以像这样使用它:
var utility = new UtilityThing<IntThing, int?>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.