动态演员 [英] Dynamic Cast

查看:86
本文介绍了动态演员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

展开 | 选择 | Wrap | 行号

推荐答案

A)谁说那不起作用?你没有说它会产生错误。

B)你的ArrayList中有什么?我们不知道您是否尝试将Cat转换为Dog或将String转换为int


如何在自定义类中创建构造函数来获取存储在数组中的信息元素?
A) Who says that doesn''t work? You haven''t said it produces an error.
B) What is in your ArrayList? We have no idea if you are trying to convert a Cat to a Dog or a String to an int

How about making a constructor in your custom class that takes the information stored in your array elements?


它不起作用,否则我不会寻求帮助。它只是不想编译。它拒绝为一个演员带一个变量Type。


在我的arraylist中,就像我说的,是自制类。
It doesnt work, else I would not be asking for help. It just doesnt want to compile. It refuse to take a variable Type for a cast.

In my arraylist, like I said, are homemade class.


的语法演员是合法的。

我确定你意识到这一点,因为你知道你可以把一个浮点数转换成一个int,例如这样的方式


float Yogi = 0.15f;

int bear =(int)Yogi;


但编译器没有水晶球。如果您有自定义类Widget和一个包含小工具的arraylist - 编译器只是不知道*它应该如何构建它。


您可能需要为不同的类编写自定义转换。
http:// msdn.microsoft.com/en-us/libr...05(SS.80).aspx


通常我正在使用从a继承的类普通班,所以VIsual Studio一般可以做到这一点(没有自定义演员功能)


级哺乳动物

级狗:哺乳动物

class Cat:哺乳动物


狗myDoberman =新狗();

Cat myTabby =(Cat)myDoberman; //法律因为他们是平等的同一父母
The syntax for the cast is legal.
I''m sure you realize this because you know you can cast a float to an int, in this way for example

float Yogi = 0.15f;
int bear = (int)Yogi;

But the compiler doesn''t have a crystal ball. If you have a custom class of "Widget" and an arraylist containing "Gadget"s - The compiler just doesn''t know *how* it should cast that.

You may need to write a custom cast for your different classes.
http://msdn.microsoft.com/en-us/libr...05(VS.80).aspx

Usually I''m working with classes that inherit from a common class, so VIsual Studio can generally do that impliticly (no custom cast function)

class Mammal
class Dog : Mammal
class Cat : Mammal

Dog myDoberman = new Dog();
Cat myTabby = (Cat)myDoberman;// Legal since they are equal classes of same parent


这篇关于动态演员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆