gpt4 book ai didi

c# - clsObject.Method() 和 new Class().Method() 的区别?

转载 作者:太空宇宙 更新时间:2023-11-03 21:57:58 25 4
gpt4 key购买 nike

假设我正在上课

Class ABC
{
public string Method1()
{
return "a";
}
public string Method2()
{
return "b";
}
public string Method3()
{
return "c";
}
}

现在我用两种方式调用这个方法:

ABC obj=new ABC();
Response.Write(obj.Method1());
Response.Write(obj.Method2());

另一种方式

Response.Write(new ABC().Method1());
Response.Write(new ABC().Method2());

以上两种方法的输出是一样的。

能否请一些人帮助我理解 obj.Method1()new ABC().Method1() 之间的区别

提前致谢..

最佳答案

objnew ABC() 是独立的实例。在您的示例中,输出是相同的,因为没有要显示的实例级数据。

试试看区别:

Class ABC
{

public string Name = "default";

public string Method1()
{
return "a";
}
}

然后使用下面的代码来显示与实例级数据的区别:

ABC obj=new ABC();
obj.Name = "NewObject";
Response.Write(obj.Method1());
Response.Write(obj.Name);

Response.Write(new ABC().Method1());
Response.Write(new ABC().Name);

关于c# - clsObject.Method() 和 new Class().Method() 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11437925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com