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

Abierto
#868 4 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
45/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
csharp, visualbasic
Área
tooling

Línea de trabajo

Reproduce la conversión de VB-to-C# del issue en el sitio web de CodeConverter y, después, sigue la ruta de conversión de VB static-local que produce el inicializador de campo. Compara la salida generada con la inicialización diferida esperada y verifica el comportamiento ante accesos repetidos y concurrentes a la propiedad; se considera terminado cuando el inicializador se difiere hasta que se usa la propiedad y el código convertido conserva la semántica requerida.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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).

Lenguaje dominante
C#
Estrellas
918
Forks
244
Merge medio
1 d 10 h
PR fusionados (30 d)
29

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de icsharpcode/CodeConverter

Todos los issues de icsharpcode/CodeConverter

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.