简体   繁体   English

将派生类的实例分配给基类的变量

[英]Assigning instance of a derived class to a variable of base class

Hello I am newbie to C# and I'm trying to figure out the "implicit conversion" operation. 您好,我是C#的新手,我正在尝试找出“隐式转换”操作。 I have a question about it: 我对此有一个疑问:

    class Animal { }
    class Monkey : Animal { }

    Monkey m = new Monkey();
    Animal a = m; 
    m.GetType()
    [Submission#165+Monkey]
    a.GetType()
    [Submission#165+Monkey]

Monkey m2 = a;// this calls - Compiler Error CS0266. Monkey m2 = a; //这将调用-编译器错误CS0266。 Cannot implicitly convert type 'Animal' to 'Monkey'. 无法将类型“动物”隐式转换为“猴子”。 An explicit 一个明确的

conversion exists (are you missing a cast?) 转换存在(您是否缺少演员表?)

I don't understand - if last code line throws an error CS0266, why does GetType method returns that "a" variable has a type "Monkey". 我不明白-如果最后一行代码抛出错误CS0266,为什么GetType方法返回“ a”变量的类型为“ Monkey”。 If "a" variable is Animal how to find it out? 如果“ a”变量是Animal,如何找到它? By what method? 用什么方法?

GetType() is evaluated at runtime. GetType()在运行时评估。 The error you are getting is at compile time, which is before the program ever runs. 您得到的错误是在编译时,即程序运行之前。

The compiler needs to ensure type safety with the information it has at compile time. 编译器需要使用编译时拥有的信息来确保类型安全。 Ensuring means making sure nothing can go wrong . 确保意味着确保不会出错 Assigning an Animal to a Monkey is, in general, not safe, because a Tiger is also an animal, so you could theoretically end up assigning a tiger to a monkey typed variable. 通常,将Animal分配给Monkey是不安全的,因为Tiger也是动物,因此从理论上讲,您最终可以将老虎分配给猴子类型的变量。

You can tell the compiler that although the assignment isn't safe, you know what you are doing. 您可以告诉编译器,尽管分配不安全,但是您知道自己在做什么。 You do this with an explicit cast: 您可以通过显式强制转换来做到这一点:

Monkey m2 = (Monkey)a;

Here you are telling the compiler; 在这里,您要告诉编译器; "Hey, I know this isn't generally safe, but trust me, I know a is a Monkey ". “嘿,我知道这通常并不安全,但是请相信我,我知道 a是一只Monkey ”。

The compiler will accept your promise but won't trust you fully, so a type check will be performed at runtime just to make sure, and if your promise is a lie, you'll get a runtime error. 编译器将接受您的承诺,但不会完全信任您,因此将在运行时执行类型检查以确保确定,并且如果您的承诺是谎言,则将收到运行时错误。

The type of the variable is Animal , the compiler will not allow you to assign this to a Monkey because an Animal is not necessarily a Monkey . 变量的类型为Animal ,编译器将不允许您将其分配给Monkey因为Animal不一定是Monkey You could assign the other way around because a Monkey is always an Animal . 您可以指定其他方式,因为Monkey 总是 Animal GetType() returns the runtime type of the object the variable points to which the compiler does not, and cannot, know anything about. GetType()返回该变量所指向的对象的运行时类型 ,编译器不知道该对象,也不知道任何相关信息。

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

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