C#generic cast

Cr3*_*0rX 11 c# generics inheritance

我有一个名为的界面 IEditor

public interface IEditor<T> 
    where T: SpecialObject
Run Code Online (Sandbox Code Playgroud)

SpecialObject 是一个抽象类.

这是我的问题:

我有一个继承自的类SpecialObject和一个实现此IEditor接口的视图

public class View : IEditor<Person>
Run Code Online (Sandbox Code Playgroud)

现在,我必须检查View是否实现 IEditor<SpecialObject>

Boolean isEditor = View is IEditor<SpecialObject>
Run Code Online (Sandbox Code Playgroud)

IEditor总是假的

有没有可能检查View是否IEditor<SpecialObject>

编辑

我有一个方法,在引发结束事件时调用.传递给此方法的视图可以实现IEditor,但它们也可以实现另一个接口.在示例IView中

  void Closing(object sender, MyEventArgs e)
  {
      if(e.Item is IView)
      {
          // DO some closing tasks

          if(e.Item is IEditor<SpecialObject>)          // always false
          {
              // Do some special tasks
              var editor = e.Item as IEditor<SpecialObject>;

              var storedEditObect = editor.StoredObject;

              // more tasks
          }
      } else if(e.Item is ISomeOtherView)
      {}
  }
Run Code Online (Sandbox Code Playgroud)

我有一些名为Person,Address等的类.它们都继承自SpecialObject.在某些情况下,e.Item继承自IEditor或IEditor因此,我必须强制转换到我的基类来访问defaut属性字段

lep*_*pie 11

创建非通用基本接口.例如:

public interface IEditor {}

public interface IEditor<T> : IEditor ... {}
Run Code Online (Sandbox Code Playgroud)

然后检查IEditor.


Jon*_*eet 10

你的问题是一般的差异.例如,a IList<MemoryStream>不是IList<Stream>.

随着C#4你可能让你的界面这样的:

public interface IEditor<out T> where T: SpecialObject
Run Code Online (Sandbox Code Playgroud)

在那时,一个IEditor<Person> IEditor<SpecialObject>- 但这只有在你的界面只用于T"out"位置时才有效.

如果这对你来说是可行的,那么它的意图可能比leppie的非通用基接口更清晰 - 但是当协方差不合适时,这是一个很好的选择.