从泛型转换为主要类型

Casting from generic to main type

我有一个 Author 对象(扩展 IModel)发送到通用方法:

IModel author = new Author() { ... };
(new Base).Method(author);

Baseclass方法:

public void Method<T>(T obj) where T : IModel {

    //does stuff
    AddToList(obj);
}

private void AddToList<T>(T obj) where T : IModel {
    if(obj is Author)
    {
        var temp = (Author)obj; // <-- this is where the error comes up
        //does stuff
    }
    else if(obj is SomethingElse)
        //...
}

如何从通用类型 (T) 转换回主要类型(Authortypeof 匹配的任何其他类型?

尝试用 obj as Auther 替换该行。应该可以。

来自https://msdn.microsoft.com/en-us/library/aa479858.aspx

看来您首先需要一个临时对象。

class MyOtherClass
{...}

class MyClass<T> 
{

   void SomeMethod(T t)
   {
      object temp = t;
      MyOtherClass obj = (MyOtherClass)temp;

   }
}