VB -> C#: Static variables are supposed to be lazy initialized inside method/property

Aberta
#868 4 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
45/100
Tipo de issue
Bug
Clareza
Razoavelmente clara
Status de atividade
Estagnada
Stack de tecnologia
csharp, visualbasic
Domínio
tooling

Direção de pesquisa

Reproduza a conversão de VB-to-C# da issue no site do CodeConverter e, em seguida, rastreie o caminho de conversão de VB static-local que produz o inicializador de campo. Compare a saída gerada com a inicialização lazy esperada e verifique o comportamento para acessos repetidos e concorrentes à propriedade; considera-se concluído quando o inicializador é adiado até que a propriedade seja usada e o código convertido preserve a semântica necessária.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

VB -> C#
VB.Net input code
Public Class VisualBasicClass

    Sub Main
        Console.WriteLine(Example)
    End Sub

    Public Readonly Property Example As Long 
        Get
            Static StaticVar As Long  = LongRunningFunction
            Return StaticVar -1 
        End Get
    End Property

    Public Shared Function LongRunningFunction As Long 
        Dim i  As Long = 1
        While i<10000000000
            i +=1
        End While  
    Return i
    End Function 
End Class
Erroneous output

public partial class VisualBasicClass
{
    public void Main()
    {
        Console.WriteLine(Example);
    }

    private long _Example_StaticVar = LongRunningFunction();

    public long Example
    {
        get
        {
            return _Example_StaticVar - 1L;
        }
    }

    public static long LongRunningFunction()
    {
        long i = 1L;
        while (i < 10000000000L)
            i += 1L;
        return i;
    }
}
Expected output

public partial class VisualBasicClass
{
    public void Main()
    {
        Console.WriteLine(Example);
    }

        private long _Example_StaticVar;
	private bool _Example_StaticVar_Init;

    public long Example
    {
        get
        {
			if (!_Example_StaticVar_Init) {
				_Example_StaticVar = LongRunningFunction();
				_Example_StaticVar_Init=true;
			}
            return _Example_StaticVar - 1L;
        }
    }

    public static long LongRunningFunction()
    {
        long i = 1L;
        while (i < 10000000000L)
            i += 1L;
        return i;
    }
}
Details
  • Website aka codeconverter.icsharpcode.net
  • Version in use: 8.4.7.0
  • Never saw it working
  • While Static variables aren't common, when using a static variable the lazy initialization is IMO essential. The "suggested" code isn't thread safe, unlike the VB code, but it's probably what most people would write as an equivalent. A more exact conversion of the Example property would be:
readonly Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag _Example_StaticVar_Init = new Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag();
 private long _Example_StaticVar;

public long Example
{
	get
	{
		bool InitStaticVariableHelper(Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag flag)
		{
			if (flag.State == 0)
			{
				flag.State = 2;
				return true;
			}
			else if (flag.State == 2)
			{
				throw new Microsoft.VisualBasic.CompilerServices.IncompleteInitialization();
			}
			else
			{
				return false;
			}
		}

		lock (_Example_StaticVar_Init)
		{
			try
			{
				if (InitStaticVariableHelper(_Example_StaticVar_Init))
				{
					_Example_StaticVar = LongRunningFunction();
				}
			}
			finally
			{
				_Example_StaticVar_Init.State = 1;
			}
		}
		return _Example_StaticVar;
	}
}

On one hand this is fairly close to an exact translation, on the other hand it's ugly. I would actually come down on the side of more exact translation (I do use it for the thread safety in a couple of places), but would understand if you felt it was too much, and the thread safety probably isn't all that important to most people (said without any basis other than a WAG).

Linguagem predominante
C#
Estrelas
918
Forks
244
Merge médio
1d 10h
PRs com merge (30d)
29

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de icsharpcode/CodeConverter

Todas as issues de icsharpcode/CodeConverter

Issues semelhantes

Mais issues de C#

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.