Menu
CoddyTech

Miembros estáticos y de instancia

Lección 35 de 48 del curso C# para desarrolladores de Rust de Coddy.

Las estructuras de Rust no tienen campos estáticos: los datos por tipo son una constante asociada o una variable estática a nivel de módulo, y un contador compartido mutable necesita un atómico o un Mutex porque escribir en una variable estática mutable requiere unsafe. Un campo estático de C# pertenece al tipo y se puede asignar como cualquier otro campo; la seguridad de los subprocesos queda a tu cargo. Los valores de las instancias deben seguir siendo independientes incluso cuando se comparte un contador de creación.

Los miembros estáticos pertenecen al tipo, no a una instancia. Son adecuados para contadores compartidos solo cuando se pretende compartirlos. Los campos de instancia siguen almacenando el valor de cada objeto. El reinicio explícito hace que este ejercicio sea repetible; evita el estado compartido oculto en diseños no relacionados.

Referencia de Rust

use std::sync::atomic::{AtomicUsize, Ordering};

static CREATED: AtomicUsize = AtomicUsize::new(0);

struct Ticket {
    value: i32,
}

impl Ticket {
    fn new(value: i32) -> Self {
        CREATED.fetch_add(1, Ordering::SeqCst);
        Ticket { value }
    }
}

fn main() {
    CREATED.store(0, Ordering::SeqCst);
    let first = Ticket::new(4);
    let second = Ticket::new(7);
    println!("{}:{}:{}", CREATED.load(Ordering::SeqCst), first.value, second.value);
}

Declaraciones auxiliares de C#

class Unit { public static string Label = "shared"; public string Name; public Unit(string name) { Name = name; } }

Instrucciones de C# dentro de Main

var a = new Unit("one");
var b = new Unit("two");
Console.WriteLine(Unit.Label + ":" + a.Name + ":" + b.Name);

Estos son fragmentos didácticos específicos. Los archivos del desafío incluyen envoltorios ejecutables completos; los fragmentos anteriores muestran las declaraciones y las instrucciones pertinentes.

Salida de referencia:

2:4:7

Salida de C#:

shared:one:two
challenge icon

Desafío

Fácil

Completa Ticket. Cada constructor almacena su semilla en Value e incrementa un contador compartido Created. Reset establece Created en cero. Solve restablece el contador, crea un ticket por cada entrada y devuelve cantidad:valores. Los valores de las instancias deben permanecer independientes.

Edita los archivos de C# desbloqueados. El archivo visible bloqueado Main.cs lee las líneas descritas, llama a Exercise.Solve, verifica que la entrada no se haya modificado e imprime el resultado con un único salto de línea final. Conserva las API declaradas. No agregues un segundo Main ni imprimas mensajes de diagnóstico.

El iniciador bloqueado también prueba de forma independiente la API de la clase o del asistente exportado, no solo el contenedor Solve.

Pruébalo tú mismo

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
Ticket.Reset(); var t1 = new Ticket(4); var t2 = new Ticket(9); if (Ticket.Created != 2 || t1.Value != 4 || t2.Value != 9) throw new Exception("Ticket API"); Ticket.Reset(); if (Ticket.Created != 0) throw new Exception("Reset API");
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de C# para desarrolladores de Rust

Practica por tu cuenta: Compilador de C# online