[英]Generic interface/base class - access members without type constraints
Suppose I have a class structure looking like this: 假设我有一个如下所示的类结构:
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>
{
}
Is there any way I can access MyObject
in any implementation of MyBaseClass
? 有什么方法可以在
MyBaseClass
任何实现中访问MyObject
吗? I can't use a variable of MyBaseClass
or MyInterface
because I have to specify type constraints, but in my case I'm not interested in specifying them since all I want to do is access the value within. 我不能使用
MyBaseClass
或MyInterface
变量,因为我必须指定类型约束,但就我而言,我对指定它们不感兴趣,因为我要做的就是访问其中的值。
Ideally I'd like to be able to do something like this: 理想情况下,我希望能够执行以下操作:
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;
What you want is not entirely possible, not with generics. 您想要的不是完全不可能的,不是泛型的。 The type
MyBaseClass
simply does not exists. 类型
MyBaseClass
根本不存在。 A generic type must have a generic type argument. 泛型类型必须具有泛型类型参数。
If you do not want to use generics, why use generics? 如果您不想使用泛型,为什么要使用泛型?
This could also be a valid option: 这也可能是有效的选择:
public interface MyInterface
{
object MyObject { get; set; }
}
public abstract class MyBaseClass : MyInterface
{
public object MyObject { get; set; }
}
Of course, in this example you have to cast the object to a specific type. 当然,在此示例中,您必须将对象转换为特定类型。
You could also combine both techniques: 您还可以结合两种技术:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.