分配类的对象 [英] Assigning objects of class

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

问题描述

  class  A 
{
}
class B:A
{
}
class Prog
{
Static < span class =code-keyword> void main()
{
A a = new A();
B b = new B();
a = b;
b = a;
}
}





我们可以分配像dis这样的对象。

解决方案

是的,你可以,但你需要清楚地了解会发生什么。这样的赋值没有创建新的对象。



由于类型是类,它是引用类型,你最终会有两个不同的引用同一个对象,当然,这通常是需要的。仅使用构造函数创建新对象。即使没有构造函数,并且使用一些工厂方法创建对象,在内部它仍然通过构造函数创建,具有堆内存分配。



你需要阅读价值和参考类型



祝你好运,

-SA






根据你的代码,我认为不可能。这是不可能的,因为Visual Studio会在b = a;时给出编译错误。原因是A是父类,B是子类。所以编译器按照''没有父对象可以分配给子对象'的规则工作。但是反之亦然。但是你可以通过强制转换来克服这个编译错误,

 b =(B) a; 

对于这种情况,这是有效的,因为在上一行你已经指定为

 a = b 

这些类是引用类型,所以在<$ p之后$ p> a = b

''''实际上是一个B类实例。如果你删除

 a = b 

那么运行时异常将被抛出

 System.InvalidCastException 

并显示消息

无法将A类型的对象强制转换为B





问候。


class A
{
}
class B :A
{
}
class Prog
{
Static void main()
{
A a=new A();
B b=new B();
a=b;
b=a;
}
}



can we assign the objects like dis.

解决方案

Yes, you can, but you need to understand clearly what happens. No new object is created by such assignment.

As the type is class, which is a reference type, you end up having two different references to the same object, which is, of course, often needed. A new object is only created with a constructor. Even if there is no constructors, and the object is created using some factory method, internally it is still created via a constructor, with heap memory allocation.

You need to read on value and reference types.

Good luck,
—SA


Hi,

According to your code I don''t think it is possible. It is not possible because Visual Studio will give a compile error at b=a;. The reason is A is the parent class and the B is the child class. So compiler works according to the rule of ''No parent object can assigned to a child object". But vice-verse is possible. But you can overcome this compile error by casting as,

b = (B)a;

For this scenario this works because at the previous line you have assigned as

a = b

These classes are reference types, so after

a = b

''a'' is actually a B class instance. If you remove the

a = b

then a run time exception will be throwed as

System.InvalidCastException

with the message

Unable to cast object of type ''A'' to type ''B''



Regards.


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

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