C# Equivalent for VB 'module'

*爱你&永不变心* 提交于 2019-12-05 17:16:10

You can use a static class. You can also initialise these using a static constructor.

public static class MyStuff
{
    //A property
    public static string SomeVariable { get; set; }

    public static List<string> SomeListOfStuff { get; set; }
    //Init your variables in here:
    static MyStuff()
    {
        SomeVariable = "blah";
        SomeListOfStuff = new List<string>();
    }

    public static async Task<string> DoAThing()
    {
        //Do your async stuff in here
    }

}

And access it like this:

MyStuff.SomeVariable = "hello";
MyStuff.SomeListOfStuff.Add("another item for the list");

A static class like this would be equivalent to your VB code:

public static class MyModule
{
    private static int iCount = 0;   // this is private, so not accessible outside this class

    public static void Increment()
    {
        iCount++;
    }

    public static bool CheckModulus()
    {
        return iCount % 6 == 0;
    }

    // this part in response to the question about async methods
    // not part of the original module
    public async static Task<int> GetIntAsync()
    {
        using (var ms = new MemoryStream(Encoding.ASCII.GetBytes("foo"))) 
        {
            var buffer = new byte[10];
            var count = await ms.ReadAsync(buffer, 0, 3);
            return count;
        }
    }
}

You would then call it like this (and the value of iCount does persist because it's static):

    // iCount starts at 0
    Console.WriteLine(MyModule.CheckModulus());   // true because 0 % 6 == 0
    MyModule.Increment();                         // iCount == 1
    Console.WriteLine(MyModule.CheckModulus());   // false
    MyModule.Increment();                         // 2
    MyModule.Increment();                         // 3
    MyModule.Increment();                         // 4
    MyModule.Increment();                         // 5
    MyModule.Increment();                         // 6
    Console.WriteLine(MyModule.CheckModulus());   // true because 6 % 6 == 0
    Console.WriteLine(MyModule.GetIntAsync().Result);   // 3

A fiddle - updated with an async static method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!