【问题标题】:C# - How to cast an object to a generic type for a subclass?C# - 如何将对象转换为子类的泛型类型?
【发布时间】:2014-12-22 15:35:49
【问题描述】:

我手头有以下代码:

class Document {}
class Track : Document {}
class Album : Document {}

class CellWrapper<T> {}

class TableViewSource {

    protected void CreateCellForItem(object item) {
        // item is an instance of CellWrapper<T> where T is a document extending Document
    }
}

是否有可能将item 转换为CellWrapper&lt;Document&gt;

我知道,您可以为我需要类似的方法定义一些东西,但我无法找到适合这种情况的东西。我只能确认(不是强制转换)它是 CellWrapper 的一个实例......

这样的东西不能编译:

CellWrapper<Document> wrapper = item as CellWrapper<T> where T : Document;

编辑

澄清一下:这个问题与Casting generic typed object to subtype 不同,因为命名的问题只有在item 是一个可枚举的对象(如IList)时才有解决方案。在我的示例中,它是一个自定义类。那里提供的解决方案不适用于我这里的问题。

【问题讨论】:

  • 你为什么要接受 object 开头的类型?
  • @YuvalItzchakov,这是界面的一部分......我无法更改它。
  • 如果您有机会在没有反思的情况下解决它,这可能会有所帮助:igoro.com/archive/…

标签: c# generics casting


【解决方案1】:

如果需要访问 T 类型的属性,可以使用反射来访问该属性。但是,这不会将值转换为CellWrapper&lt;Document&gt;

class Document {
    public string Key { get; set; }
}
class Track : Document {}
class Album : Document { }

class CellWrapper<T> where T : Document {
    public T Document { get; set; }
}

class TableViewSource
{

    public void CreateCellForItem(object item)
    {
        var documentProperty = item.GetType().GetProperty("Document");
        var document = (Document)documentProperty.GetValue(item);
        Console.WriteLine(document.Key);
    }
}

【讨论】:

    【解决方案2】:

    就这个:

     CellWrapper<Document> wrapper = item as CellWrapper<Document>;
    

    【讨论】:

    • 如果您有 CellWrapper&lt;Track&gt;CellWrapper&lt;Album&gt; 的实例,则会失败 ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多