【发布时间】:2018-11-15 14:59:51
【问题描述】:
我是出于好奇而问这个问题,并且我知道其他方法。
我想知道,如果某个方法返回某种类型的对象,我们可以直接修改该对象的属性(即时 - 无需将其引用到局部变量中)。
为什么我们需要将它的引用引入局部变量来改变对象本身?
在编译器级别可能存在限制程序员这样做的逻辑困难。
参见下面的示例代码:
static Demo StaticDemoInstance;
static void Main(string[] args)
{
//allowed: means I can directly modify property of static instance
// received from method
GetDemo().Name = "UpdateDemo";
//allowed: means I can get instance and overwrite it with other instance
// but not directly from method
Demo d = GetDemo();
d = new Demo("NewCreatedDemo", false);
//not allowed: means I can't do second step directly on method
// question:
// when I can update instance property without receiving instance on local variable
// what possible violation/difficulty (in compiler) will be there so it doesn't allow this
GetDemo() = new Demo("UpdatedDemoFromGetMeth", false);
}
static Demo GetDemo() => StaticDemoInstance ??
StaticDemoInstance = new Demo("StaticDemo", false);
【问题讨论】:
-
GetDemo() = new Demo("UpdatedDemoFromGetMeth", false);你是……没有分配属性……GetDemo()是一种方法……当心投票者。 -
@BagusTesa 是的,我知道.. 我已经写了这个问题本身
GetDemo().Name = "UpdateDemo";我正在设置属性 -
好吧,您可以在下面看到@TheGeneral 的答案,但它仅适用于 C#7.0。我仍然坚持 5.
-
您为什么要这样做,而不是仅仅将
GetDemo()设为可写的Demo属性? -
@BagusTesa 那么你不能......就这么简单:-) 请注意,即使使用
ref,您也只能ref使用局部变量或字段,而不是属性。所以它的用途有点有限。
标签: c# object methods reference