假设我的类结构如下所示:
public abstract class MyOtherBaseClass
{
public string HelloWorld;
}
public interface MyInterface<T> where T : MyOtherBaseClass
{
T MyObject { get; set; }
}
public abstract class MyBaseClass<T> : MyInterface<T>
where T : MyOtherBaseClass
{
public T MyObject { get; set; }
}
public class MyImplementation : MyBaseClass<MyOtherBaseClass>
{
}
在MyObject
的任何实施中,我有什么办法可以访问MyBaseClass
吗?我无法使用MyBaseClass
或MyInterface
的变量,因为我必须指定类型约束,但在我的情况下,我对指定它们并不感兴趣,因为我想做的就是访问其中的值。
理想情况下,我希望能够做到这样的事情:
MyBaseClass baseObject = null;
if(someCondition)
{
baseObject = new MyImplementation();
}
else if(otherCondition)
{
baseObject = new OtherImplementation(); //this also inherits from MyBaseClass
}
var objectValue = baseObject.MyObject;
var helloWorldValue = objectValue.HelloWorld;
答案 0 :(得分:1)
你想要的并非完全可能,而不是泛型。类型MyBaseClass
根本不存在。泛型类型必须具有泛型类型参数。
如果您不想使用泛型,为什么要使用泛型?
这也可能是一个有效的选择:
public interface MyInterface
{
object MyObject { get; set; }
}
public abstract class MyBaseClass : MyInterface
{
public object MyObject { get; set; }
}
当然,在此示例中,您必须将对象强制转换为特定类型。
您还可以结合使用这两种技术:
public interface MyInterface // This is the non-generic interface.
{
object MyObject { get; set; }
}
public interface MyInterface<T> // This is the generic interface.
where T : MyOtherBaseClass
{
T MyObject { get; set; }
}
public abstract class MyBaseClass<T> : MyInterface, MyInterface<T> // This class implements both the non-generic and the generic interface.
where T : MyOtherBaseClass
{
public T MyObject { get; set; } // Implementation of the generic property.
object MyInterface.MyObject // Implementation of the non-generic property.
{
get { return MyObject; }
set { MyObject = (T)value; }
}
}
...
MyInterface baseObject; // The non-generic interface is used as base object.
baseObject = new MyImplementation(); // It is assigned an instance of MyImplementation which uses a generic base class.
object value = baseObject.MyObject;