简体   繁体   English

无法将类别转换为C#中的通用类别

[英]Unable to cast a class to a generic class in C#

I'm new to C# generics so please bear with me. 我是C#泛型的新手,所以请多多包涵。 I wanna cast an object of type (say)NodeRef to NodeRef<TNode>. 我想将类型(例如)NodeRef的对象转换为NodeRef <TNode>。 Is it possible? 可能吗? If, yes How ? 如果是,如何? Currently this is what I have 目前这就是我所拥有的

public class Program
{
    static void Main(string[] args)
    {
        var nodeRef = new NodeRef();
        var newNodeRef = (NodeRef<MyNode>) nodeRef;
        //above line throws up at Runtime.
    }
}

public class NodeRef
{
    private int id;
}

public class NodeRef<TNode> : NodeRef
{
    private TNode tNode;

    public void Print()
    {
      Console.WriteLine(tNode.ToString());
    }
}

I'm currently getting this exception: System.InvalidCastException. 我目前遇到此异常:System.InvalidCastException。

Edit: 编辑:

Why won't it throw a compile time error, though ? 但是,为什么它不会引发编译时错误? MyNode is just a dummy class MyNode只是一个虚拟类

public class MyNode 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

This problem is not because you are using generics. 此问题不是因为您使用的是泛型。 The problem is that NodeRef<T> is a NodeRef . 问题在于NodeRef<T> NodeRef But not all NodeRef are necessarily NodeRef<T> . 但并非所有NodeRef都一定是NodeRef<T> It depends on what you wrote when you first called new . 这取决于您首次调用new时写的内容。

This would also happen if you wrote your derived object to look like this: 如果您编写派生对象看起来像这样,也会发生这种情况:

public class SomeDerivedClass : NodeRef
{
    // ...
}

static void Main(string[] args)
{
    var nodeRef = new NodeRef();
    var newNodeRef = (SomeDerivedClass) nodeRef;
}

For a cast to work you have to cast to the same type as your actual instance (the type you specified when you called new ), or one of its base classes. 为了使转换有效,您必须转换为与实际实例相同的类型(调用new时指定的类型)或其基类之一。 For example, this code will not throw an exception: 例如,此代码不会引发异常:

public class Program
{
    static void Main(string[] args)
    {
        NodeRef nodeRef = new NodeRef<MyNode>();
        var newNodeRef = (NodeRef<MyNode>) nodeRef;
    }
}

Casts like this don't convert the type of the object instance to another type (unless you write a custom conversion operator, which you didn't do here). 这样的强制类型转换不会将对象实例的类型转换为另一种类型(除非您编写了自定义转换运算符,而您在这里没有这样做)。 These types of cast simply let you tell the compiler "I know the object is actually this other type. Let me work with it that way". 这些类型的强制转换只是让您告诉编译器“我知道对象实际上是另一种类型。让我以这种方式使用它”。 If you make a mistake, the .Net framework will throw an exception when you are running the program. 如果您输入有误,.Net框架将在运行程序时引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM