【问题标题】:Generic interface/base class - access members without type constraints通用接口/基类 - 访问没有类型约束的成员
【发布时间】:2016-01-15 08:27:12
【问题描述】:

假设我有一个如下所示的类结构:

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>
{

}

有什么方法可以在MyBaseClass 的任何实现中访问MyObject?我不能使用MyBaseClassMyInterface 的变量,因为我必须指定类型约束,但就我而言,我对指定它们不感兴趣,因为我只想访问其中的值。

理想情况下,我希望能够做这样的事情:

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;

【问题讨论】:

  • this also inherits from MyBaseClass 来自MyBaseClass&lt;MyOtherBaseClass&gt; 或来自其他具体类型。
  • @HamletHakobyan 对不起,MyBaseClass&lt;MyOtherBaseClass&gt;。每个实现都可以创建自己的派生类型MyOtherBaseClass 并使用它,例如MyBaseClass&lt;MyDerivedOtherBaseClass&gt;

标签: c# generics inheritance interface


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    相关资源
    最近更新 更多