簡體   English   中英

通用接口/基類-無類型約束的訪問成員

[英]Generic interface/base class - access members without type constraints

假設我有一個如下所示的類結構:

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;

您想要的不是完全不可能的,不是泛型的。 類型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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM