Property backing value scope

前端 未结 6 1315
情书的邮戳
情书的邮戳 2021-02-12 19:10

Is anything like this possible? I\'m assuming not, but it looks good to me:

class MyClass {
    public int Foo {
        get { return m_foo; }
        s         


        
6条回答
  •  时光说笑
    2021-02-12 19:39

    The short answer is no, that's not possible in C# today.

    We get a feature request like this fairly often; it's a nice feature in its more general form. The more general form is to more clearly make the lifetime of a local variable orthogonal to its scope.

    Just to make sure those terms are clear: a variable is a storage location, possibly named. Every variable has a lifetime: the amount of time at runtime in which the variable is guaranteed to refer to valid storage. The scope of a name is the region of text in which that name may be used; it is a compile-time concept, not a runtime concept. A local variable is a variable whose scope is a statement block.

    In many languages, the lifetime of a local variable is closely tied to its scope: when control logically enters the scope at runtime, the lifetime begins and when it leaves the scope, the lifetime ends. This is true in C# with some notable caveats:

    • The lifetime of a local may be extended or truncated if the runtime can determine that doing so has no consequence to the action of managed code on the current thread. The actions of other threads (like the finalizer thread) and unmanaged code on the current thread are implementation-defined.

    • The lifetime of a local that is in an iterator block, an async method, or a closed-over outer variable of an anonymous function, may be extended to match or exceed the lifetime of the iterator, task, delegate or expression tree that uses it.

    Clearly it is not a requirement that the lifetime and scope of a local be tied together in any way. It would be nice if we could explicitly have locals that have the lifetime of an instance or static field, but the scope of a local. C has this feature; you can make a "static" local variable. C# does not. Your proposal is essentially to allow a local variable within the block of the property that has the lifetime of the instance but whose scope is restricted to the block.

    I would classify this feature as "nice". We have a list of potential "nice" features literally as long as your arm that we don't have time to implement, so I wouldn't expect this one to make it to the top of the list any time soon. Thanks for the feedback though; it helps us prioritize that list somewhat.

提交回复
热议问题