本文介绍了C#中:保持ref参数在类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我希望能够有一个类的实例中一个变量的引用,但我想引用成为一个类变量,所以我不需要周围发送它的类作为参数的内部



代码:

  INT NUM = 0; 
MyClass的(NUM);
打印张数; //输出为0,但我想它是10 :)
类myClass的
{
私人诠释classNumber;
MyClass的(参考INT数)
{
打印数量; //输出为0

//这样ID是对refenrence
classNumber参考=号;

DoSomething的();
}
公共无效DoSomething的()
{
ClassNumber = 10;
}
}



为什么我问这个是因为我用的WinForms工作,具有主窗体发送一个类的实例,以新的形式,应该编辑类,并发送回..现在我使用Form.ShowDialog(),以避免用户使用的主要形式,而编辑新的形式,之后抓住来自新形式

  editForm edtfrm =新editForm(REF instanceOfClass)中的数据; 
edtfrm.showDialog();
//抢实例重新
instanceOfClass = edtfrm.editedClass;



我怎样才能解决这个问题?我不喜欢这种解决方案


解决方案

You will have to live with disappointment then. The CLR type system explicitly forbids storage of references to variables as members of classes. The CLR permits references to variables to be

  • passed to methods as arguments corresponding to formal parameters or 'this'
  • stored as locals
  • returned as method return values

but does not permit storage in arrays, fields, and so on. Basically, anything that goes "on the heap" can't hold onto a ref.

C# exposes the first feature: refs to variables as method parameters. It does not expose the other two features (though I have written an experimental version of C# which does, and it works quite nicely.)

Note that C# does not allow you to use refs in contexts which would require heap storage of the ref -- like a ref parameter being a closed-over outer variable of a lambda, for example. There are a few rare cases in which the compiler does allow what looks like long-term storage of the ref, and uses copy-in-copy-out semantics to emulate the ref, but probably best to not even go there.

Why does the CLR have this restriction? The right way to think about it is that there are two kinds of storage: long term and short term, usually called "heap" and "stack". But the shape of the data structure is irrelevant; what is relevant is the length of the lifetime. A variable has a storage location; that's what a variable is. If you could keep a ref to a variable allocated from the short-term storage in a long-term storage then the long-term storage keeps a ref to something that is of shorter lifetime, and therefore might crash and die when it accesses the variable after its death.

Obviously there are many ways to solve this problem. For example, the CLR team could have chosen to make it illegal to take a ref to short-term storage, and allow storage of refs in long-term storage. But that then means that you can't take refs to local variables or parameters, which you would like to put in short-term storage because their lives are so short.

The way the CLR team actually chose was to disallow long-term storage of any ref. Like any design decision, it was the result of many tradeoffs against competing goals.

这篇关于C#中:保持ref参数在类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:06
查看更多