简体   繁体   中英

C# functions with static data

In VB.Net, I can declare a variable in a function as Static, like this:

Function EncodeForXml(ByVal data As String) As String
    Static badAmpersand As Regex = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)")

    data = badAmpersand.Replace(data, "&")

    ''// more processing

    return data
End Function

Note that I need to use the keyword Static , rather than Shared , which is the normal way to express this in VB.Net. How can I do this in C#? I can't find its equivalent.

Ha! In posting the question, I found the answer! Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me. After applying that insight, I found this:
http://weblogs.asp.net/psteele/articles/7717.aspx

That article explains that it's not really supported by the CLR, and the VB compiler creates a static (shared) variable "under the hood" in the method's class. To do the same in C#, I have to create the variable myself.

More than that, it uses the Monitor class to make sure the static member is thread-safe as well. Nice.

As a side note: I'd expect to see this in C# sometime soon. The general tactic I've observed from MS is that it doesn't like VB.Net and C# to get too far apart feature-wise. If one language has a feature not supported by the other it tends to become a priority for the language team for the next version.

Personally I'm glad that C# doesn't have this. Logically, methods don't have state: types and instances do. C# makes that logical model clearer, IMO.

There is no equivalent in C# unfortunately.

You will need to use a class level variable.

This is one of the few things that VB has that I wish C# had.

你必须在类级别声明:

private static readonly RegEx badAmpersand = new RegEx("...");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM